You are trying to modify s in-place, but after each replacement of 'a' with "aaa", you are not skipping the new as you just inserted, so you end up replacing them as well, ie water -> waaater -> waaaaater -> waaaaaaater, and so on in an endless loop until an error occurs.
Try this instead:
#include <iostream> #include <string.h> using namespace std; int main () { char s[100], t[100]; int i, j; cout << "The string is: " << endl; cin.get (s, 100); strcpy (t, s); for (i = 0, j = 0; i < strlen (s); i++, j++) { if (s[i] == 'a') { strcat (strcpy (s + i, "aa"), t + j); i += 2; } } cout << "The modified string is: " << endl; cout << s; }
Demo
Alternatively:
#include <iostream> #include <string.h> using namespace std; int main () { char s[100]; cout << "The string is: " << endl; cin.get(s, 100); int len = strlen(s); for (int i = 0; i < len; i++) { if (s[i] == 'a') { if ((len+3) > sizeof(s)) break; // no more space! memmove(s+(i+3), s+(i+1), sizeof(s)-(i+1)); s[i+1] = 'a'; s[i+2] = 'a'; i += 2; len += 2; } } cout << "The modified string is: " << endl; cout << s; }
Demo
However, if you use std::string instead of char[], you can then use the std::string::find() and std::string::replace() methods, eg:
#include <iostream> #include <string> using namespace std; int main () { string s; cout << "The string is: " << endl; cin >> s; string::size_type pos = 0; do { pos = s.find('a', pos); if (pos == string::npos) break; s.replace(pos, 1, "aaa"); pos += 3; } while (true); cout << "The modified string is: " << endl; cout << s; }
Demo
Alternatively, use std::string::insert() instead, eg:
#include <iostream> #include <string> using namespace std; int main () { string s; cout << "The string is: " << endl; cin >> s; string::size_type pos = 0; do { pos = s.find('a', pos); if (pos == string::npos) break; s.insert(pos, "aa"); // or: s.insert(pos, 2, 'a'); pos += 3; } while (true); cout << "The modified string is: " << endl; cout << s; }
Demo
std::string??std::string, will it work?a, in which case it writes three times, advancing after each. Be sure to terminate the target string when done, and of course, limit check.sand if you find anayou insert 2 moreaintosbut then the next letter insis one that you just inserted so then you insert 2 more and then 2 more ... until you run out of space in s. To fix it, every time you insert intosyou need to increase the index intosby 2 so you can get past what you just inserted - but you can't increase the index intotbecause you didn't insert anything intot. And that means you need two indexes: one forsand one fort: onlinegdb.com/r1Nuxzn7u