Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# .Replace() method does not work correctly with Arabic language

Tags:

c#

I am using .Replace() method to replace a placeholder [CITY] in arabic language.

public static void Main()
{
    Console.WriteLine("Hello World");
    var replace = "سنغافورة";
    var input = "ABC [CITY] مرحبا بالعالم";
    Console.WriteLine(input);
    var final = input.Replace("[CITY]", replace);
    Console.WriteLine(final);
}

I get the following output

ABC [CITY] مرحبا بالعالم
ABC سنغافورة مرحبا بالعالم

As you can see the city instead of being placed next to ABC is added at the extreme right.

This issue happens only for arabic and works fine for other languages (english/thai/spanish etc)

Not sure whats going wrong here.

C# fiddle - https://dotnetfiddle.net/mvIcHt

like image 969
Yasser Shaikh Avatar asked Jun 13 '19 11:06

Yasser Shaikh


2 Answers

Using this answer: This

I've edited your code for that:

public static void Main()
{
    Console.WriteLine("Hello World");
    var replace = "سنغافورة";
    var input = "York Hotel في [CITY] – عروض الغرف، صور وتقييمات";
    Console.WriteLine(input);
    var lefttoright = ((Char)0x200E).ToString();
    var final = input.Replace("[CITY]", lefttoright + replace + lefttoright );
    Console.WriteLine(final);

}

And the output is:

Hello World
York Hotel في [CITY] – عروض الغرف، صور وتقييمات
York Hotel في ‎سنغافورة‎ – عروض الغرف، صور وتقييمات

Citing @Takarii:

Char 0x200E is a special character that tells the following text to read left to right see here for more information on the character.

like image 101
Mikev Avatar answered Oct 16 '22 17:10

Mikev


Just add an RTL mark at the beginning of your Arabic text:

public static void Main()
{
    Console.WriteLine("Hello World");

    const char rtl = (char)0x200E;
    var replace = "سنغافورة";

    var input = "York Hotel في [CITY] – " + rtl + "عروض الغرف، صور وتقييمات";
    Console.WriteLine(input);
    var final = input.Replace("[CITY]", replace);
    Console.WriteLine(final);
}

Update: Adopted the answer from here: https://stackoverflow.com/a/44961348/6193089

like image 23
Dmitri Trofimov Avatar answered Oct 16 '22 17:10

Dmitri Trofimov