Search code examples
c++stringinsertspace

Adding a space before a character in a string C++ insert function


I am attempting to add space before a character in a string by using the insert function.

Can someone kindly explain why the following code does not work ?

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

Solution

  • If you want to insert before = you can get the index of = directly and not the index of char followed by =. This could lead to out of bounds access.

    Also, when you insert the space you extend your string by 1, that's ok but only if you also adjust the counter i, otherwise it will insert again and again and again before = resulting in infinite loop. Adjust your code in this manner:

    for (int i = 0; i < line.length(); i++)
    {
        if (line[i] == '=')
        {
            line.insert(i++, " ");
        }
    }