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

  1. Start with Text A😀
  2. Do this Count code points
  3. Result 2
The emoji occupies two UTF-16 units but represents one code point.

Apply it to a real problem

  1. Start with A shipping label A🚲
  2. Do this Count units, then count code points
  3. Result 3 units, 2 code points
A label limit must specify which measure it uses for supplementary characters.
Advertisements

Run the example

Save as Main.java and run java Main.java with JDK 21.

Main.java
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é"));
    }
}
Output
3 units, 2 code points
true

Official Java documentation