How to insert a character at a specific position in string: answered! | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
0

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

12th Oct 2020, 6:18 AM
The_Fox
The_Fox - avatar
9 Réponses
+ 1
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.
12th Oct 2020, 7:44 AM
Brian
Brian - avatar
+ 3
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.
12th Oct 2020, 7:13 AM
Brian
Brian - avatar
+ 2
The code that would do the insertion is missing. Were those lines deleted?
12th Oct 2020, 6:29 AM
Brian
Brian - avatar
+ 1
Thank you. I will try that.
12th Oct 2020, 7:15 AM
The_Fox
The_Fox - avatar
+ 1
@Martin: thanks, I already referenced that section ;)
12th Oct 2020, 8:51 AM
The_Fox
The_Fox - avatar
0
I originally used something like str.insert(“_“) but do not know how to get the correct position.
12th Oct 2020, 6:31 AM
The_Fox
The_Fox - avatar
0
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
12th Oct 2020, 7:13 AM
The_Fox
The_Fox - avatar
0
Thanks Brian, that really helped a lot!
12th Oct 2020, 8:49 AM
The_Fox
The_Fox - avatar
12th Oct 2020, 9:02 AM
The_Fox
The_Fox - avatar