UnicodeScript Identifies Character Script
Character.UnicodeScript.of maps each code point to its writing script, letting validation route Latin, Han, or Hiragana input by script.
Code
import java.util.LinkedHashMap;
import java.util.Map;
public class ScriptDetection {
public static void main(String[] args) {
// UnicodeScript.of identifies the script of each character
// 'A' 拉丁、'あ'(U+3042)平假名、'数'(U+6570)汉字、'Ω'(U+03A9)希腊
String[] samples = {"A", "あ", "数", "Ω", "1"};
// 按文字分桶:同一 script 的字符归到一组
Map<Character.UnicodeScript, StringBuilder> byScript = new LinkedHashMap<>();
for (String sample : samples) {
Character.UnicodeScript script = Character.UnicodeScript.of(sample.charAt(0));
byScript.computeIfAbsent(script, k -> new StringBuilder()).append(sample);
}
byScript.forEach((script, chars) -> System.out.println(script + " <- " + chars));
// 数字与标点不属于任何文字:COMMON
System.out.println("digit script: " + Character.UnicodeScript.of('1'));
// forName 支持按枚举名查回同一个常量
System.out.println(Character.UnicodeScript.forName("LATIN"));
}
}Script lookup per code point
Character.UnicodeScript.of(sample.charAt(0)) maps one code point to its Unicode script constant. The demo feeds "A" (Latin), "あ" U+3042 (Hiragana), "数" U+6570 (Han), "Ω" U+03A9 (Greek), and "1" into a LinkedHashMap<Character.UnicodeScript, StringBuilder>, so computeIfAbsent buckets characters by script while preserving first-seen order.
Buckets and one-off lookups
LATIN <- A
HIRAGANA <- あ
HAN <- 数
GREEK <- Ω
COMMON <- 1
digit script: COMMON
LATIN
The digit lands in COMMON — digits and punctuation belong to no writing system, which the file’s comment calls out as the routing case for validation. The final line shows Character.UnicodeScript.forName("LATIN") resolving the same constant by enum name, useful when a configuration file names scripts as strings.
The line that classifies a character
Character.UnicodeScript script = Character.UnicodeScript.of(sample.charAt(0));
One call per character is the whole detection primitive — the map is just grouping, so a validator can route Latin, Han, or Hiragana input by script with a single switch.
Interactive Tools for This Topic
FAQ
- What does UnicodeScript Identifies Character Script print when run?
- The script runs standalone; its 1 labeled outputs include `digit script:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.