StringBuilder Reverse Surrogate Pairs

StringBuilder.reverse() treats each surrogate pair as one unit so emoji survive reversal, while a manual char-by-char loop splits them into lone surrogates.

JavaData Integrity

Code

snippet
public class TextReverser {

    public static void main(String[] args) {
        // emoji 是一对 char(代理对):字符串按 char 计数比按代码点多一
        String label = "go \uD83D\uDE80!";
        System.out.println("chars   = " + label.length());

        // 错误做法:按 char 手动逆序,代理对被拆散成两个孤立代理项
        StringBuilder naive = new StringBuilder();
        for (int i = label.length() - 1; i >= 0; i--) {
            naive.append(label.charAt(i));
        }
        System.out.println("naive   = " + naive);

        // StringBuilder.reverse 按代码点处理 surrogate pairs,emoji 完整保留
        System.out.println("reverse = " + new StringBuilder(label).reverse());
    }
}

Where the work happens

Structurally, expect the class TextReverser and the function main and nothing else.

for (int i = label.length() - 1; i >= 0; i--) does the per-item lifting.

Points of care

  • Nothing beyond the language’s own toolchain is required.

Applying it

The entry-point signature is public static void main(String[] args)

The file’s steps show up in the output as chars =, naive =, reverse =.

Statements that matter

StringBuilder naive = new StringBuilder();
String label = "go \uD83D\uDE80!";
naive.append(label.charAt(i));

Interactive Tools for This Topic

FAQ

What does StringBuilder Reverse Surrogate Pairs print when run?
Invoke the file as-is — the `chars =`, `naive =`, `reverse =` prefixes identify which step printed each line.