-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 Answers2

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' );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
-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.

Appleshell
  • 7,088
  • 6
  • 47
  • 96