Yasser Shaikh
Yasser Shaikh

Reputation: 47784

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

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

Upvotes: 7

Views: 661

Answers (2)

Mikev
Mikev

Reputation: 2082

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.

Upvotes: 2

Dmitri Trofimov
Dmitri Trofimov

Reputation: 763

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

Upvotes: 1

Related Questions