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
Release: 2024-12-21 12:57:20
Original
539 people have browsed it

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);
}
Copy after login

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!"
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template