Home >Backend Development >C++ >How to Replace All Occurrences of a Character in a C String?

How to Replace All Occurrences of a Character in a C String?

DDD
DDDOriginal
2024-12-21 12:57:20540browse

How to Replace All Occurrences of a Character in a C   String?

Replacing All Occurrences of a Character in a String

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 header, which operates on iterators, to effectively accomplish this task.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn