什么是有效的方法来取代一个字符的所有出现与另一个字符在std::字符串?


当前回答

一个简单的查找和替换单个字符是这样的:

s.find("x"), 1, "y")

要对整个字符串执行此操作,最简单的方法是循环,直到s.find开始返回npos。我认为您还可以捕获range_error来退出循环,但这有点丑陋。

其他回答

对于简单的情况,无需使用任何其他库就可以很好地工作,然后使用std::string(已经在使用)。

将some_string中出现的所有字符a替换为字符b:

for (size_t i = 0; i < some_string.size(); ++i) {
    if (some_string[i] == 'a') {
        some_string.replace(i, 1, "b");
    }
}

如果字符串很大,或者有多个需要替换的调用,您可以应用这个答案中提到的技术:https://stackoverflow.com/a/29752943/3622300

这不是标准库中缺少的唯一方法,它本来是低级别的。 这个用例和许多其他用例由通用库涵盖,例如:

波科 绳降 提高 QtCore

QtCore & QString有我的偏好:它支持UTF8,使用更少的模板,这意味着可以理解的错误和更快的编译。它使用了“q”前缀,使命名空间变得不必要,并简化了头文件。 Boost经常生成可怕的错误消息和缓慢的编译时间。 POCO似乎是一种合理的妥协。

如何替换任何字符串与任何字符串仅使用良好的旧C字符串函数?

char original[256]="First Line\nNext Line\n", dest[256]="";
char* replace_this = "\n"; // this is now a single character but could be any string
char* with_this = "\r\n"; // this is 2 characters but could be of any length

/* get the first token */
char* token = strtok(original, replace_this);

/* walk through other tokens */
while (token != NULL) {
    strcat(dest, token);
    strcat(dest, with_this);
    token = strtok(NULL, replace_this);
}

Dest现在应该有我们要找的东西了。

Std::string不包含这样的函数,但你可以使用独立的替换函数从算法头。

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

正如Kirill建议的那样,要么使用replace方法,要么沿着字符串迭代,单独替换每个字符。

或者,您可以使用find方法或find_first_of,这取决于您需要做什么。这些解决方案都不能一次性完成工作,但是通过几行额外的代码,您应该让它们为您工作。: -)