Java 不同语言的字符串错序拼接

Java String wrong order concatenation of different languages

因此,正如您从图像中看到的那样,我已将 a、c 和 b 连接起来。我得到了我预期的结果。 但是在第二个 println 中,当我连接 a、e 和 b 时,我最终连接了 e,而不是我期望的位置。 我想知道这种行为的原因和解决方案。 提前谢谢你。

import java.util.*;
public class prob 
{
    public static void main(String... args)
    {
        String a="الف",b="1/2",c="ب",e="B";

        System.out.println(a+" : "+c+" : "+b);
        System.out.println(a+" : "+e+" : "+b);
    }
}

编辑(解释为什么我的问题不是重复的): 我的问题是将 L2R 语言转换为 R2L。

这是因为第一个字符是 R2L(在亚洲语言中是从右到左的方向),所以下一个字符在开头(正确的方向):

第一个字符:

الف 
// actual orientation ←

第二个字符添加到 L

// add ←
B : الف 
// actual orientation →

在此之后,B 在欧洲通常是 L2R,因此在 B 之后以正确的方向添加下一个字符 (1/2):

// → add in this direction
B : 1/2 : الف 
// actual orientation → (still)

您可以通过复制粘贴字符并手动编写另一个来轻松测试它,您将看到方向如何根据您插入的字符而变化。


更新:

what is my solution for this issue, because i made this example only to show what issue i was facing in making some big reports, where data is mix sometimes, it is L2R String and sometimes R2L. And i want to make a string in strictly this format.(

来自this answer

  • Left-to-right embedding (U+202A)
  • Right-to-left embedding (U+202B)
  • Pop directional formatting (U+202C)

So in java, to embed a RTL language like Arabic in an LTR language like English, you would do

myEnglishString + "\u202B" + myArabicString + "\u202C" + moreEnglish

and to do the reverse

myArabicString + "\u202A" + myEnglishString + "\u202C" + moreArabic

See (for the source material)


添加 2:

char l2R = '\u202A';
System.out.println(l2R + a + " : " + e +" : "+b);

输出:

‪الف : B : 1/2

正如在此 中所述,原因是某些字符串具有从右到左的方向。

对于从右到左方向的字符串,可以手动设置方向为letf-to-right,用\u200e控制character,如:

String a="\u200eالف",b="1/2",c="\u200eب",e="B";

System.out.println(a+" : "+c+" : "+b);
System.out.println(a+" : "+e+" : "+b);