How to replace all occurrences of a character in string?

后端 未结 15 1251
别那么骄傲
别那么骄傲 2020-11-22 05:54

What is the effective way to replace all occurrences of a character with another character in std::string?

15条回答
  •  情深已故
    2020-11-22 06:25

    For simple situations this works pretty well without using any other library then std::string (which is already in use).

    Replace all occurences of character a with character b in some_string:

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

    If the string is large or multiple calls to replace is an issue, you can apply the technique mentioned in this answer: https://stackoverflow.com/a/29752943/3622300

提交回复
热议问题