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.
Code
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
Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.