想我會添加一個以foreach循環(ref)工作的變通辦法,再加上你可以當你移動到Java 8很容易轉換成Java 8的新的String#代碼點方法:
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();
}
};
}
};
}
然後你可以用foreach使用它像這樣:
for(int codePoint : codePoints(myString)) {
....
}
或者交替,如果你只是想將一個字符串轉換成int數組(這可能會使用更多的內存比上面的方法):
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;
}
至於它是否「昂貴」,那麼......沒有其他方式構建到Java中。但是,如果您只處理拉丁/歐洲/西里爾/希臘/希伯來語/阿拉伯語腳本,那麼您只需將s.charAt()放入您的內容。 :) – 2009-10-06 20:25:32
但你不應該。例如,如果你的程序輸出XML,並且如果有人給它一個模糊的數學運算符,突然你的XML可能是無效的。 – 2012-07-15 01:18:59
@Jonathan Feinberg這就是我的想法。但是在這裏出現了特殊的數學E. UTF-16在99%的時間內工作 - 但後來變得非常痛苦。特別是當問題長期處於隱藏狀態時。 – Martin 2014-02-09 13:12:34