You are trying to modify s
in-place, but after each replacement of 'a'
with "aaa"
, you are not skipping the new a
s 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