简体   繁体   中英

Replace() differences between C#/C++

I've been trying to wean myself into learning C# by converting some of my old C++ console apps. I'm aware that C# similarly has string.Replace; however I'm having a hard time getting this method to do what it's cpp counterpart function does, which is replace select characters within user input.

C++

string str;

getline(cin, str);

for (char &i : str){

        replace(str.begin(), str.end(), 'a', '4');
        replace(str.begin(), str.end(), 'A', '4');
                ...
               }
cout << "Translated text: " << str << endl;
}

C#

string str;

str = Console.ReadLine();

foreach (char c in str){

    str.Replace('a','4');
    str.Replace('A', 4');
}
Console.WriteLine("Translated Text: " + str);
}

C# strings are immutable, so any method which changes them returns a new string instead of modifying the original.

str = str.Replace('a','4');
str = str.Replace('A', 4');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM