String Comparison
Comparing Unicode strings requires normalization (NFC/NFD) and optionally collation (locale-aware sorting). Binary comparison of code points alone gives incorrect results for equivalent strings.
What is Unicode String Comparison?
Unicode string comparison is the process of determining whether two Unicode strings are equal, or which comes first in a sorted order. It sounds simple, but Unicode's encoding flexibility makes naive byte-by-byte comparison unreliable. The same text can be encoded in multiple valid ways, and language-specific sorting rules vary enormously across the world's scripts and locales.
Binary Comparison Pitfalls
The most obvious approach — comparing strings byte-by-byte or code-point-by-code-point — fails silently in many real-world situations. Consider the character é. It can be encoded as:
- U+00E9 — a single precomposed code point (NFC form)
- U+0065 U+0301 — the base letter e followed by a combining acute accent (NFD form)
These two sequences are canonically equivalent under the Unicode Standard but are binary-unequal. A naive comparison would declare them different strings, even though they represent identical text. This causes bugs in search, deduplication, password checks, and username lookups.
NFC Normalization Before Comparing
The standard defense is to normalize both strings to the same Unicode normalization form before comparing. NFC (Canonical Decomposition followed by Canonical Composition) is the recommended form for most applications because it produces compact, precomposed forms that work well with legacy systems.
import unicodedata
a = "e\u0301" # e + combining acute (NFD-style)
b = "\u00e9" # precomposed é (NFC-style)
a == b # False — binary comparison
unicodedata.normalize("NFC", a) == unicodedata.normalize("NFC", b) # True
Always normalize to NFC before storing usernames, email addresses, or any text that will be compared for equality.
Locale-Aware Collation with ICU
Sorting order is a separate problem from equality. In English, ä typically sorts near a, but in Swedish, ä sorts after z. In French, accents are compared from right-to-left as a tiebreaker. These rules are formalized in the Unicode Collation Algorithm (UCA) and implemented by the ICU library (International Components for Unicode).
In Python, the pyuca package or the locale module provide UCA-based sorting. In JavaScript, Intl.Collator wraps ICU directly.
// JavaScript locale-aware sort
const words = ["ä", "z", "a"];
words.sort(new Intl.Collator("sv").compare); // Swedish: ["a", "z", "ä"]
words.sort(new Intl.Collator("de").compare); // German: ["a", "ä", "z"]
Case-Insensitive Comparison via Case Folding
Converting both strings to lowercase before comparing does not work correctly across all scripts. Unicode defines case folding (documented in CaseFolding.txt) as a locale-independent way to erase case distinctions for comparison purposes. Case folding handles edge cases like the German ß, which folds to ss, and the Greek capital letter sigma Σ, which folds to σ.
# Python case folding
"Straße".casefold() == "STRASSE".casefold() # True
Quick Facts
| Property | Value |
|---|---|
| Key pitfall | Canonically equivalent strings are binary-unequal |
| Recommended normalization | NFC for general text, NFD for internal processing |
| Collation standard | Unicode Collation Algorithm (UCA), CLDR locale rules |
| ICU library | International Components for Unicode |
| Case folding spec | Unicode CaseFolding.txt (UCD) |
| Python module | unicodedata (normalize, casefold) |
| JS API | Intl.Collator, String.prototype.normalize() |
관련 용어
알고리즘의 더 많은 용어
Mapping characters to a common case form for case-insensitive comparison. More comprehensive …
Rules (UAX#29) for determining where one user-perceived character ends and another begins. …
정규화 형식 C: 분해 후 정규 재합성하여 가장 짧은 형식을 생성합니다. 데이터 …
정규화 형식 D: 재합성 없이 완전히 분해합니다. macOS HFS+ 파일 시스템에서 사용됩니다. …
정규화 형식 KC: 호환 분해 후 정규 합성. 시각적으로 유사한 문자를 통합합니다(fi→fi, …
정규화 형식 KD: 재합성 없이 호환 분해. 가장 강력한 정규화 방식으로 서식 …
유니코드 단어 경계 규칙에 따라 결정된 단어 사이의 위치. 단순히 공백으로 분리하는 …
유니코드 규칙에 따른 문장 사이의 위치. 마침표로만 분리하는 것보다 복잡하며, 약어(Mr.), 생략 …
문자 양방향 범주와 명시적 방향 재정의를 사용하여 혼합 방향 텍스트(예: 영어 + …
유니코드 텍스트를 표준 정규 형식으로 변환하는 과정. 네 가지 형식: NFC(합성), NFD(분해), …