user562854
user562854

Reputation:

C# String.Replace and UTF-8 chars

I am trying to replace some of the Romanian characters in this string with my own chars, but it's not really working.

static void Main(string[] args)
{
    string sometext = "Încă nu s-a pornit acasă";
    sometext.Replace("ă", "1");

    Console.WriteLine(sometext);
    Console.ReadKey(true);
}

This outputs the original sometext without any changes. However, neither without replacing nor with replacing the final result is Inca nu s-a pornit acasa. Diacritics are replaced with the ISO-8859-1 characters corresponding to them. Î becomes I, ă becomes a.

Sumarry:

The expected result is: Înc1 nu s-a pornit acas1.

Actually, I get: Inca nu s-a pornit acasa

Note: In Advanced Save Options, I've selected the following encoding: Unicode (UTF-8 with signature) - Codepage 65001

Acutally, strings are immutable and String.Replace returns a string, so sometext = sometext.Replace("ă", "1"); works just fine. Thanks to all!

Upvotes: 2

Views: 3902

Answers (4)

Nika G.
Nika G.

Reputation: 2384

static void Main(string[] args)
{
    string sometext = "Încă nu s-a pornit acasă";
    sometext = sometext.Replace("ă", "1");

    Console.WriteLine(sometext);
    Console.ReadKey(true);
}

try this...

Upvotes: 2

HasaniH
HasaniH

Reputation: 8402

Replace does not mutate the string, it returns a string with the replacements so your code should be:

sometext = sometext.Replace(...);

Upvotes: 6

Allen Rice
Allen Rice

Reputation: 19446

static void Main(string[] args)
{
    string sometext = "Încă nu s-a pornit acasă";
    sometext = sometext.Replace("ă", "1");

    Console.WriteLine(sometext);
    Console.ReadKey(true);
}

or

static void Main(string[] args)
{
    string sometext = "Încă nu s-a pornit acasă".Replace("ă", "1");

    Console.WriteLine(sometext);
    Console.ReadKey(true);
}

or whatever, Replace returns the string

Upvotes: 3

user195488
user195488

Reputation:

Strings are immutable. So do sometext = sometext.Replace(...).

Upvotes: 2

Related Questions