简体   繁体   中英

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

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?

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 \‎ character. In the case of this string:

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

will do the trick.

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.

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