In C , the std::string class does not provide a dedicated method for replacing characters in a string. However, you can utilize the std::replace function from the
Consider the following code snippet:
#include <algorithm> #include <string> void replace_character(std::string& str, char old, char new) { std::replace(str.begin(), str.end(), old, new); }
The replace_character function takes a reference to a string, the character to be replaced (old), and the replacement character (new). It uses the std::replace function to modify all occurrences of old with new within the string.
For example:
std::string str = "Hello, world!"; replace_character(str, 'l', 'x'); // Output: "Hexxo, worxd!"
This code snippet replaces all occurrences of the character 'l' with 'x' in the string str. Note that the original string is modified in-place.
The above is the detailed content of How to Replace All Occurrences of a Character in a C String?. For more information, please follow other related articles on the PHP Chinese website!