循环 Unicode 代码点
获取字符串中每个字符的Unicodecode point编号。
通过调用String#codePointCount获取代码点数。
然后通过调用String#codePointAt 循环每个代码点。请注意,我们必须使用烦人的从零开始的计数,而不是序数,这是从编程早期开始就非常常见且不幸的保留习惯。
String input = "Hi?" ;
int countCodePoints = input.codePointCount( 0 , input.length() ) ;
for( int i = 0 ; i < countCodePoints ; i ++ )
{
System.out.println( "i: " + i + " | " + input.codePointAt( i ) ) ;
}
看到这个code run live at IdeOne.com。
i: 0 | 72
i: 1 | 105
i: 2 | 128512
避免char
不幸的是,此页面上的其他答案使用 char 类型。该类型现在是 legacy,可以追溯到 Java 的原始版本。
该类型已过时,因为它甚至无法处理 Unicode 中定义的 143,859 个字符中的一半。为了好玩,运行这段代码来看看当我们使用char 类型来查看上面看到的相同输入字符串时会发生什么:"Hi?".chars().forEach( c -> System.out.println( c ) ) 。
您的解决方案
回到您输入文本的具体示例:
String input = "ABC" ;
int countCodePoints = input.codePointCount( 0 , input.length() ) ;
for( int i = 0 ; i < countCodePoints ; i ++ )
{
System.out.println( "i: " + i + " | " + input.codePointAt( i ) ) ;
}
运行时:
i: 0 | 65
i: 1 | 66
i: 2 | 67
既然是作业,那我就把减法和倒数的工作留给你。
补充阅读:The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!).