How to insert a character at a specific position in string: answered!
Hey there. I‘m looping through a string of characters and want to insert a character at position where a condition is met. It somehow does not work correctly and I am stuck... Any tips? https://code.sololearn.com/cV2GX2p71K9p/?ref=app
There is more to say about the fixes that I recommended. You can eliminate all that special handling of the index i and len variables by simply running the loop backward! for(int i=len-1; i>=0; i--) That way there is no need to adjust for inserted characters. Now, instead of printing each character inside the loop, wait until after the loop finishes, then just do one cout << str.
Andrebot okay that helps to know you tried with str.insert(). Here is what you will need to complete it. The position for insert is the same as index i. Use str.insert(i, "_"). Now there is a new problem: That insert shifts the capital letter into position i+1. So the next iteration of i tests the same letter that it just tested, and then it inserts another "_", and the cycle repeats. You must increment i specially to account for the inserted "_" character and get past the capital letter. Also add a cout to show the new "_" character. Since the string length changes, also update the len variable, else the loop will stop short of the end of the string.
The code that would do the insertion is missing. Were those lines deleted?
Thank you. I will try that.
@Martin: thanks, I already referenced that section ;)
I originally used something like str.insert(“_“) but do not know how to get the correct position.
I have this other version but it only works for two cases of when condition is met (here uppercase)... https://code.sololearn.com/c056qCQB7Ex9/?ref=app
Thanks Brian, that really helped a lot!
@Brian : Final version! https://code.sololearn.com/cV2GX2p71K9p/?ref=app