以为我会添加一种适用于foreach循环(ref)的解决方法,另外,当您移至Java 8时,可以轻松地将其转换为Java 8的新String#codePoints方法:
您可以将它与foreach一起使用,如下所示:
for(int codePoint : codePoints(myString)) {
....
}
这是助手的方法:
public static Iterable<Integer> codePoints(final String string) {
return new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int nextIndex = 0;
public boolean hasNext() {
return nextIndex < string.length();
}
public Integer next() {
int result = string.codePointAt(nextIndex);
nextIndex += Character.charCount(result);
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
或者,如果您只想将字符串转换为int数组(可能比上述方法使用更多的RAM),请执行以下操作:
public static List<Integer> stringToCodePoints(String in) {
if( in == null)
throw new NullPointerException("got null");
List<Integer> out = new ArrayList<Integer>();
final int length = in.length();
for (int offset = 0; offset < length; ) {
final int codepoint = in.codePointAt(offset);
out.add(codepoint);
offset += Character.charCount(codepoint);
}
return out;
}
值得庆幸的是,使用“ codePoints”可以安全地处理UTF-16(Java的内部字符串表示形式)的代理配对。