How can I replace all occurrences of a character with another character in std string?

H

herman

How can I replace all occurrences of a character with another
character in std string?

For example, I want to replace '/' with '+' in my std::string

I have looked at the replace() method in the string class, it does not
replace all occurrences of a character with another character.

http://www.cppreference.com/cppstring/index.html

Thank you
 
I

Ian Collins

herman said:
How can I replace all occurrences of a character with another
character in std string?

For example, I want to replace '/' with '+' in my std::string

I have looked at the replace() method in the string class, it does not
replace all occurrences of a character with another character.
You either have to roll your own, or look at a regular expression
library like boost.regexp:

http://www.boost.org/libs/regex/doc/introduction.html
 
M

Matthew Crisanti

herman said:
How can I replace all occurrences of a character with another
character in std string?

For example, I want to replace '/' with '+' in my std::string

Try using std::for_each with a functor. For example

struct testfunctor
{
void operator()(char& c) { if(c == '/') c = '+'; }
};
....
std::string str("This is a test - /////////\n");
std::cout << str;
std::for_each( str.begin(), str.end(), testfunctor() );
std::cout << str;
 
D

dilipk3

How can I replace all occurrences of a character with another
character in std string?

For example, I want to replace '/' with '+' in my std::string

I have looked at the replace() method in the string class, it does not
replace all occurrences of a character with another character.

http://www.cppreference.com/cppstring/index.html

Thank you

var str;
str.replace(///g,'+');

/g is for universal char i.e all char in string.
 
B

BobR

herman said:
How can I replace all occurrences of a character with another
character in std string?

For example, I want to replace '/' with '+' in my std::string

I have looked at the replace() method in the string class, it does not
replace all occurrences of a character with another character.

http://www.cppreference.com/cppstring/index.html

Thank you

// #include <algorithm>
std::string rep( "?Hello?, ?World?" );
std::replace( rep.begin(), rep.end(), '?', '+' );
cout<<"replace ="<<rep<<std::endl;
// out: replace =+Hello+, +World+
 
?

=?ISO-8859-1?Q?Erik_Wikstr=F6m?=

var str;
str.replace(///g,'+');

/g is for universal char i.e all char in string.

The other people in this group use the C++ language, what do you use?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top