Replacing All Character Occurrences in a String
Question:
How can I efficiently replace all occurrences of a specific character with another character in a std::string in C ?
Answer:
While std::string does not provide a built-in function for this, you can utilize the stand-alone replace function from the algorithm header. Here's how:
#include <algorithm> #include <string> void replace_characters(std::string& s, char old_char, char new_char) { std::replace(s.begin(), s.end(), old_char, new_char); // replace all old_char with new_char in s }
Example:
int main() { std::string s = "example string"; replace_characters(s, 'x', 'y'); // replace all 'x' with 'y' std::cout << s << std::endl; // Output: "example string" with 'x' replaced by 'y' return 0; }
The above is the detailed content of How to Efficiently Replace All Character Occurrences in a C String?. For more information, please follow other related articles on the PHP Chinese website!