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


当前回答

老派:-)

std::string str = "H:/recursos/audio/youtube/libre/falta/"; 

for (int i = 0; i < str.size(); i++) {
    if (str[i] == '/') {
        str[i] = '\\';
    }
}

std::cout << str;

结果:

点:youtube \ resources \音响\ \‘\ \缺失

其他回答

Abseil StrReplaceAll怎么样?在头文件中:

// This file defines `absl::StrReplaceAll()`, a general-purpose string
// replacement function designed for large, arbitrary text substitutions,
// especially on strings which you are receiving from some other system for
// further processing (e.g. processing regular expressions, escaping HTML
// entities, etc.). `StrReplaceAll` is designed to be efficient even when only
// one substitution is being performed, or when substitution is rare.
//
// If the string being modified is known at compile-time, and the substitutions
// vary, `absl::Substitute()` may be a better choice.
//
// Example:
//
// std::string html_escaped = absl::StrReplaceAll(user_input, {
//                                                {"&", "&amp;"},
//                                                {"<", "&lt;"},
//                                                {">", "&gt;"},
//                                                {"\"", "&quot;"},
//                                                {"'", "&#39;"}});

对于简单的情况,无需使用任何其他库就可以很好地工作,然后使用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

如何替换任何字符串与任何字符串仅使用良好的旧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现在应该有我们要找的东西了。

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

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

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'
}