Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all occurrences of a character in string?

What is the effective way to replace all occurrences of a character with another character in std::string?

like image 234
big-z Avatar asked May 24 '10 11:05

big-z


People also ask

How do you replace all occurrences of a character in a string in C++?

In C++, the STL provides a function to replace() to change the contents of an iterable container. As string is a collection of characters, so we can use the std::replace() function to replace all the occurrences of character 'e' with character 'P' in the string.

How do you replace all occurrences of a character in a string in TypeScript?

To replace all occurrences of a string in TypeScript, use the replace() method, passing it a regular expression with the g (global search) flag. For example, str. replace(/old/g, 'new') returns a new string where all occurrences of old are replaced with new .

How do you replace all occurrences of a character in Python?

The replace() method replace() is a built-in method in Python that replaces all the occurrences of the old character with the new character.

How do you remove all occurrences of a character from a string in JavaScript?

Delete all occurrences of a character in javascript string using replaceAll() The replaceAll() method in javascript replaces all the occurrences of a particular character or string in the calling string. The first argument: is the character or the string to be searched within the calling string and replaced.


1 Answers

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm> #include <string>  void some_func() {   std::string s = "example string";   std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y' } 
like image 93
Kirill V. Lyadvinsky Avatar answered Dec 06 '22 22:12

Kirill V. Lyadvinsky