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

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

Linda Hamilton
Linda HamiltonOriginal
2024-12-28 01:05:09609browse

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

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!

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