You can't replace a single-byte char
with a multi-byte character using operator[]
. You need to do something more like this instead:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("Hello this is The friend");
string::size_type i = 0;
while (i < str.size())
{
if ((str[i] == 'T') || (str[i] == 't'))
{
str[i] = '1';
str.insert(i+1, 'Y');
// or:
// str.replace(i, 1, "1Y");
i += 2;
}
else
++i;
}
cout << str;
}
Alternatively:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str("Hello this is The friend");
string::size_type i = 0;
while ((i = str.find_first_of("Tt", i)) != string::npos)
{
str[i] = '1';
str.insert(i+1, 'Y');
// or:
// str.replace(i, 1, "1Y");
i += 2;
}
cout << str;
}
Alternatively:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string str("Hello this is The friend");
ostringstream oss;
for (string::size_type i = 0; i < s.size(); ++i)
{
if ((s[i] == 'T') || (s[i] == 't'))
oss << "1Y";
else
oss << s[i];
}
cout << oss.rdbuf();
}