开发者

Problem creating correct path concatenating left to right with right to left sections

开发者 https://www.devze.com 2023-01-30 23:57 出处:网络
I have simplified in a big way the problem and here is the sample code: string outputString = string.Empty;

I have simplified in a big way the problem and here is the sample code:

string outputString = string.Empty;
string joinOutputString = string.Empty;
string pathOutputString = string.Empty;

string[] myStrings = new string[4];
myStrings[0] = "First entry";
myStrings[1] = "اول";
myStrings[2] = "دوم";
myStrings[3] = "Last entry";

StringBuilder sb = new StringBuilder();

for (int i = 0; i < myStrings.Length; i++)
{
    joinOutputString = string.Join(@"\", joinOutputString, myStrings[i]);
    outputString = string.Format(@"{0}{1}\", outputString, myStrings[i]);
    pathOutputString = System.IO.Path.Combine(pathOutputString, myStrings[i]);
    sb.Append(string.Format(@"{0}\", myStrings[i]));
}
开发者_StackOverflow社区

The final value of all strings and StringBuilder at the end of the loop is:

First entry\اول\دوم\Last entry\

instead of

First entry\دوم\اول\Last entry\

The middle right to left section is flipped as one unit.

Thanks for your time in advance.


You have a bidi string (a string containing both LTR and RTL characters) and .NET is switching between LTR and RTL modes when outputting the string. Punctuation is considered "weak" and continues using whatever direction is currently active. So you output a LTR string ("First entry") followed by a string of RTL characters (3 from myString[1] + "\" + 3 from myString[2]) followed by a LTR string ("Last entry").

myString[0] (printed LTR) then myString[1] (printed RTL) then myString[2] (printed RTL) then myString[3] (printed LTR)

Note that the entire middle string (composed of myString[1] + "\" + myString[2]) is printed RTL and hence transposed from your expectation. You can add a pseudo-strong LTR mark (Unicode character 0x200E) to force the direction change.

http://en.wikipedia.org/wiki/Bi-directional_text

In your code:

joinOutputString = string.Join("\\\x200E", joinOutputString, myStrings[i]);

Note the \ is an escaped \ and \x200E is the pseudo-strong LTR mark.


It would be easier to do the following

System.IO.Path.Combine(myStrings);

if you are attempting to make a path.

0

精彩评论

暂无评论...
验证码 换一张
取 消