CodePointDemo.java
Download CodePointDemo.java
1: // This class shows how to work with I18n strings, since not
2: // all Unicode characters (code points) can be stored in a Java
3: // "char" (or code unit). So to iterate over the characters in
4: // a string the old code of:
5: // for ( int i=0; i<str.length(); ++i) {
6: // char c = str.charAt(i); ...;
7: // }
8: // needs to be converted to something like the for loop shown below.
9: //
10: // Written 1/2010 by Wayne Pollock, Tampa Florida USA
11:
12: import static java.lang.Character.toChars;
13: import static java.lang.Integer.toHexString;
14: import static java.lang.String.*;
15: import static java.lang.System.*;
16:
17: public class CodePointDemo
18: {
19: public static void main ( String [] args )
20: {
21:
22: // If user supplies a string (word), use it; else
23: // use a sample string containing weird Unicode:
24: String str = args != null && args.length>0 ?
25: args[0] : "A G-clef: \"\uD834\uDD1E\".";
26:
27: // For each character, do something:
28: for ( int i=0; i<str.length(); i = str.offsetByCodePoints(i, 1) ) {
29: int cp = str.codePointAt(i);
30:
31: // To demo how, show the index, the char (may not display
32: // correctly without an appropriate font), and the hex values:
33: out.println( i + ": \"" + new String(toChars(cp))
34: + "\" (0x" + toHexString(cp) + ")" );
35: }
36: }
37: }