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