Why does this code, written backwards, print “Hello World!”

后端 未结 5 1507
有刺的猬
有刺的猬 2020-12-02 04:14

Here is some code that I found on the Internet:

class M‮{public static void main(String[]a‭){System.out.print(new char[]
{\'H\',\'e\',\'l\',\'l\',\'o\',\' \'         


        
5条回答
  •  心在旅途
    2020-12-02 04:40

    It looks different because of the Unicode Bidirectional Algorithm. There are two invisible characters of RLO and LRO that the Unicode Bidirectional Algorithm uses to change the visual appearance of the characters nested between these two metacharacters.

    The result is that visually they look in reverse order, but the actual characters in memory are not reversed. You can analyse the results here. The Java compiler will ignore RLO and LRO, and treat them as whitespace which is why the code compiles.

    Note 1: This algorithm is used by text editors and browsers to visually display characters both LTR characters (English) and RTL characters (e.g. Arabic, Hebrew) together at the same time - hence "bi"-directional. You can read more about the Bidirectional Algorithm at Unicode's website.
    Note 2: The exact behaviour of LRO and RLO is defined in Section 2.2 of the Algorithm.

提交回复
热议问题