[Solved] Weird Behavior while inserting a character into string in C++


I don’t know what you’re trying to accomplish but your code has a few logical bugs.

Perhaps you intended to do s1.substr(i, 4) instead of s1.substr(i, i+4). The second argument of substr is length.

Even after doing this you might enter infinite loop because the length of the string is increasing by 1 every-time you insert and you recheck from the same index.

This should be logically more correct than your code:

for(int i=0;i<s1.length()-4;i++)
{
   if(i>0 && s1.substr(i,4)=="2(0)" && s1.at(i-1)!='+')
     s1.insert(i-1,1,'+');
   i++;
}

solved Weird Behavior while inserting a character into string in C++