-3

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".

scopchanov
  • 7,966
  • 10
  • 40
  • 68

2 Answers2

3

The implementation of std::string is std::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?

vdavid
  • 2,434
  • 1
  • 14
  • 15
  • The solution pointed to in the link suffer from the same problem as the OP's solution. The replace family in algorithm replace character for character. A custom solution creating a modified version of the original string could be in order. – Michael Surette Aug 15 '18 at 23:24
1

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();
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770