I am trying to change "Hello this is The friend" to "Hello 1Yhis is 1Yhe friend"
#include <iostream>
using namespace std;
int main()
{
string str("Hello this is The friend");
for ( int i = 0 ; i < str.size(); i++)
{
if (str[i] == 'T')
{
str[i] = '1Y';
}else if (str[i] == 't')
{
str[i] = '1Y';
}
}
cout<<str;
}
The output is "Hello Yhis is Yhe friend".
The implementation of
std::stringisstd::basic_string<char>, which means you can only use single-characters in it.You are making use of an illegal multi-character constant
'1Y'. I guess your compiler warned you about that. Because he cannot insert a multi-character, the compiler chose one for you, i.e.'Y'in your case.If you want to replace chars with something else than another single-character, you should take a look at solutions such as How to replace all occurrences of a character in string?