Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Search/Find and Replace in a standard string?

Tags:

c++

replace

std

Is there a way to replace all occurrences of a substring with another string in std::string?

For instance:

void SomeFunction(std::string& str) {    str = str.replace("hello", "world"); //< I'm looking for something nice like this } 
like image 630
Adam Tegen Avatar asked Sep 29 '09 19:09

Adam Tegen


People also ask

How do you replace an element in a string?

Python String | replace() replace() is an inbuilt function in the Python programming language that returns a copy of the string where all occurrences of a substring are replaced with another substring. Parameters : old – old substring you want to replace. new – new substring which would replace the old substring.

How do you use the Replace function in string?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.


2 Answers

#include <boost/algorithm/string.hpp> // include Boost, a C++ library ... std::string target("Would you like a foo of chocolate. Two foos of chocolate?"); boost::replace_all(target, "foo", "bar"); 

Here is the official documentation on replace_all.

like image 155
10 revs Avatar answered Sep 20 '22 19:09

10 revs


Why not implement your own replace?

void myReplace(std::string& str,                const std::string& oldStr,                const std::string& newStr) {   std::string::size_type pos = 0u;   while((pos = str.find(oldStr, pos)) != std::string::npos){      str.replace(pos, oldStr.length(), newStr);      pos += newStr.length();   } } 
like image 35
yves Baumes Avatar answered Sep 18 '22 19:09

yves Baumes