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

浪尽此生 提交于 2019-12-10 16:16:30

问题


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]));
}

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.


回答1:


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.




回答2:


It would be easier to do the following

System.IO.Path.Combine(myStrings);

if you are attempting to make a path.



来源:https://stackoverflow.com/questions/4475067/problem-creating-correct-path-concatenating-left-to-right-with-right-to-left-sec

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!