Java對字符串使用Unicode/UTF-16,而不是ASCII。
如果要限制您的方法來處理ASCII範圍內的字符,它應該在遇到該範圍之外的情況下引發異常。
如果你想要一個「字符代碼」(aka碼點)的序列,你必須在方法中使用String.codePointAt()
。由於String
包含一個統計的UTF-16代碼單元序列,並且每個代碼點可能有一個或兩個代碼單元,因此您只知道String.length()
是預先提供的代碼點數的上限。
public class Q1E {
int[] stringToCodes(String s) {
int[] codepoints = new int[s.length()]; // there might be fewer
int count = 0;
for(int cp, i = 0; i < s.length(); i += Character.charCount(cp)) {
cp = s.codePointAt(i);
// for debugging, output in Unicode stylized format
System.out.println(String.format(
cp < 0x10000 ? "U+%04X" : "U+%05X", cp));
codepoints[count++] = cp;
}
int[] array = java.util.Arrays.copyOf(codepoints, count);
return array;
}
}
與一個英文單詞本維基百科的鏈接嘗試:
stringToCodes("http://en.wikipedia.org/wiki/Résumé");
你忘了你的方法的最後返回'array'。 – 2014-10-09 04:35:57
改變'length(characters);'用'characters.length();'否則你的代碼甚至不會編譯。 – Rustam 2014-10-09 04:44:18