Reverse a string in Java

前端 未结 30 2591
礼貌的吻别
礼貌的吻别 2020-11-21 13:12

I have \"Hello World\" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there

30条回答
  •  被撕碎了的回忆
    2020-11-21 14:09

    As others have pointed out the preferred way is to use:

    new StringBuilder(hi).reverse().toString()
    

    But if you want to implement this by yourself, I'm afraid that the rest of responses have flaws.

    The reason is that String represents a list of Unicode points, encoded in a char[] array according to the variable-length encoding: UTF-16.

    This means some code points use a single element of the array (one code unit) but others use two of them, so there might be pairs of characters that must be treated as a single unit (consecutive "high" and "low" surrogates).

    public static String reverseString(String s) {
        char[] chars = new char[s.length()];
        boolean twoCharCodepoint = false;
        for (int i = 0; i < s.length(); i++) {
            chars[s.length() - 1 - i] = s.charAt(i);
            if (twoCharCodepoint) {
                swap(chars, s.length() - 1 - i, s.length() - i);
            }
            twoCharCodepoint = !Character.isBmpCodePoint(s.codePointAt(i));
        }
        return new String(chars);
    }
    
    private static void swap(char[] array, int i, int j) {
        char temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    
    public static void main(String[] args) throws Exception {
        FileOutputStream fos = new FileOutputStream("C:/temp/reverse-string.txt");
        StringBuilder sb = new StringBuilder("Linear B Syllable B008 A: ");
        sb.appendCodePoint(65536); //http://unicode-table.com/es/#10000
        sb.append(".");
        fos.write(sb.toString().getBytes("UTF-16"));
        fos.write("\n".getBytes("UTF-16"));
        fos.write(reverseString(sb.toString()).getBytes("UTF-16"));
    }
    

提交回复
热议问题