This is really ticking me off.


Ok I have a program like so:-

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string crap = "dfgfd-rergreg-dfgfdg-ertertd-gfdg-df";
}

And all I wanna do is replace the "-" with " - " . Note the spaces.


I've tried everything but it won't work.

Shit like this won't work. Why?

for ( int i = 0; i < crap.length(); i++)
{
  if (crap[i] =='-')
  {
   crap.replace(i,1," - ");
  }
}

wtf?

I think it is not a problem with replace as such, but it is a problem with your algorithm. Since you are replacing "-" with " - ", the next character after the original "-" will become "-". So your code will become an infinite loop. Try replacing "-" with " x ", and then your code should replace characters properly.

Ok that works dave.

But I woulda never thought of that.

#include <iostream>
#include <string>
#include <vector>

[B]using namespace[/B] std;

[B]int[/B] main()
{
    string crap = "dfgfd-rergreg-dfgfdg-ertertd-gfdg-df";
    
    [B]for[/B] ( [B]int[/B] i = 0; i < crap.length(); i++)
    {
     [B]if [/B](crap[i] =='-')
     {
      crap.replace(i,1," zzzz--zzz ");
      i+=6; //why 6
     }
     
    }
    cout << crap;
    cin.get();
    [B]return[/B] 0;
}

It seems you have to increment it by the index where the first repeat occurs. If no repeats occur in the replacement string this appears not to be a problem?

It seems you have to increment it by the index where the first repeat occurs.

You have to increment it by the "maximum index where '-' occurs in the replacement string".
For " - " increment is 1. : Maximum Index = 1
For " zzzz--zzz " increment is 6, Maximum Index = 6
For " zzzz--zz - z " increment is 13, Maximum Index = 13

Edit:
But the easiest will be to increment it from length of replacement string - 1. Because you are sure that there is no need of searching inside that part again.

But the easiest will be to increment it from length of replacement string - 1. Because you are sure that there is no need of searching inside that part again.

Ok that makes more sense.

arggggggggg!

Back to square one.

string tmp = "-8-7-3-2-3";
int len = 0;
len = tmp.length();
for( int i = 0; i < len; i++ )
{
      if ( tmp[i]=='-')
      {
          tmp.replace(i,1," - ");
          i+=2;
      }
}

I need the output to look like:-

- 8 - 7 - 3 - 2 - 3

But instead I get:-

- 8 - 7 - 3-2-3

That is because it is going only upto the old string length. You must update the search string length too. Put

len = tmp.length();

Inside the if block after the replace.

ok that appeared to do the trick.

I think I might read up on iterators, to iterate through a string.

This article has been dead for over six months. Start a new discussion instead.