-2

I am currently trying to replace a single character in a string with more than one number. Lets make it quick:

replace(string.begin(), string.end(), 'a', '1'); 

^ WORKS! ^

replace(string.begin(), string.end(), 'a', '11'); 

or

replace(string.begin(), string.end(), 'a', "1"); 

^ DOESN'T WORK! ^

How do I do it? Is there any function for it?

NOTE: I'm not asking how to:

  • Replace part of a string with another string
  • Replace substring withanother substring
2
  • 4
    Aside: '11' is a multi-character-literal, having type int. It is most likely not remotely what you think it is. Commented May 9, 2014 at 13:18
  • And BTW, this question is not even a part of those 'already answered' questions! Can you people even read? Commented May 9, 2014 at 13:45

2 Answers 2

0

You should use some overloaded member function replace of class std::basic_string instead of the standard algorithm std::replace.

For example

for ( std::string::size_type pos = 0; ( pos = s.find( 'a', pos ) ) != std::string::npos; pos += 2 ) { s.replace( pos, 1, 2, '1' ); } 

Or if the number can be any arbitrary string then you can write

std::string number( "123" ); for ( std::string::size_type pos = 0; ( pos = s.find( 'a', pos ) ) != std::string::npos; pos += number.size() ) { s.replace( pos, 1, number ); } 

If you want to replace a number with a character then you can write

for ( std::string::size_type pos = 0; ( pos = s.find( "11", pos ) ) != std::string::npos; ++pos ) { s.replace( pos, 2, 1, 'a' ); } 
Sign up to request clarification or add additional context in comments.

4 Comments

The first one works! Thanks alot man! :)
Emm... how can I do it in reverse? Like number to alphabet? Example: 'a' to 123 then 123 to 'a'?
Nevermind, I've figured it out. Thanks again :)
@Marwan Ansari See my updated post. In general you should use together member functions find and replace of class std::string.
-1

You need to give the same type of argument as the value to be replaced and the replacing value.

'a' is a char, while "1" is a string. You can't mix those two, replace in this case only supports chars.

Note: '11' is not a valid char.

4 Comments

That explains why the OP's approach doesn't work. But he was asking for a way to achieve what he wants.
Regarding your edit: '11' might be valid for certain implementations. See this question for example.
@lethal-guitar It's of type int and not of type char.
@AdamS fair enough. Still, it will possibly compile without error. I'd add that it is a "multi-character literal".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.