Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace in strings which contain Persian and English letters together in C#

Tags:

string

c#

replace

This is the string :

         str="[@PEYear]/ف/[@POOL]"

I want to replace it, base on this structure:

        if (str.Contains("[@PEYear]"))
            str = str.Replace("[@PEYear]", "1393");
        if (str.Contains("[@POOL]"))
            str = str.Replace("[@POOL]", "7");

The result is : 1393/ف/7

But I need : 1393 then ف and then 7 (even I can't type it here :P)

How can I do this?

like image 681
Alale sa Avatar asked Feb 03 '26 05:02

Alale sa


2 Answers

I'll expand on Lucas's answer a bit. Suppose you have this string:

String str = "1393" + "/" + "ف" + "/" + "&"

Where "&" = "7", because the stackoverflow edit window autocorrects when there's a numeral (try substituting a 7 for the & in the above). This evaluates to "1393/ف/7".

This is because the string concatenation function, as soon as it encounters a right to left character, appends the rest of the characters to the left of this character. So, since this string has 8 characters, and the 6th character is RTL, the characters are ordered (if you start with zero) 01234765.

Now this (note that I can type in the 7 now without getting autocorrected):

String str = "1393" + "/" + "ف" + "\u200e" + "/" + "7"

evaluates to "1393/ف‎/7", which is what you want. So, if you're receiving the string as you have it, and so can't modify it directly in your code, you can use the Substring method to manipulate the incoming string to insert the \u200e character. In the case of this string:

str = str.Substring(0,6) + "\u200e" + str.Substring(6,2)

will do the trick.

like image 198
BobRodes Avatar answered Feb 05 '26 18:02

BobRodes


I don't know if this solution would be acceptable to you, but it works if you insert a left-to-right mark:

var str = "[@PEYear]/ف\u200E/[@POOL]";

This will force the rest of the string to be left-to-right.

like image 38
Lucas Trzesniewski Avatar answered Feb 05 '26 19:02

Lucas Trzesniewski