Count characters in a shipping label in Java
Two labels can look identical while using different Unicode sequences. Normalize text before comparing it and count code points when supplementary characters matter.
A simple example
Count code points
- Start with Text A😀
- Do this Count code points
- Result 2
Apply it to a real problem
- Start with A shipping label A🚲
- Do this Count units, then count code points
- Result 3 units, 2 code points
Advertisements
Run the example
Save as Main.java and run java Main.java with JDK 21.
import java.text.Normalizer;
public class Main {
public static void main(String[] args) throws Exception {
String label = "A🚲";
System.out.println(label.length() + " units, " + label.codePointCount(0, label.length()) + " code points");
String accent = Normalizer.normalize("Cafe\u0301", Normalizer.Form.NFC);
System.out.println(accent.equals("Café"));
}
}
3 units, 2 code points true