在D中搜索和替换字符串

Mat*_*ane 1 d

我在D中编写了一些代码,并试图确定一种在字符串中搜索字符串的通用方法,并将其替换为可能具有不同长度的另一个字符串.

例如,像这样的东西:

string x = "123XX456XX789";
auto y = search_and_replace(x, "XX", "DIFFERENT");
assert (y == "123DIFFERENT456DIFFERENT789");
Run Code Online (Sandbox Code Playgroud)

Ada*_*ppe 5

很简单,replace标准库中的功能就是这样:

import std.array; // or std.string works too but std.array has the generic one
auto y = replace(x, "XX, "DIFFERENT");
Run Code Online (Sandbox Code Playgroud)

  • 是的,如果你不知道他们做了什么,很多文档很难阅读; 它们是精美的复习或参考,但是学习材料很差.很多字符串相关的东西在D中也比在很多其他语言中更通用,因此可以在`std.array`甚至`std.algorithm`中找到,而不是`std.string`的第一个猜测... .(虽然通用的东西很好,你也可以在字节数组或int数组或其他任何东西上使用它们!) (4认同)