面试官:String类的 charAt 方法返回值是什么?
侯选人:返回的是 String类 中对应位置的字符 Unicode 值。
面试官:错,pass了。
首选 Java 中String类是以UTF-16编码来存储的,我们定义一个 字符串 ,这个字段串会先用
UTF -16进行编码,编码之后的值以char数组的形式存储在String类的value属性里。
在 维基百科 中, UTF-16 编码的定义如下:
从上面,我们可以看出一个字符经过UTF-16编码之后需要1个或者2个16位码元(Java中一个char占16位)存储,因此charAt方法返回值有以下两种情况:
1、string中某个位置字符的unicode值,此时该字符在UTF-16中以一个码元存储。
2、string中某个位置字符UTF-16编码后的第一个码元值或第二个码元值,此时该字符以2个码元来表示。
那问题来了,如果要返回string中某个字符的unicode值怎么办?
这时候应该用codePointAt方法。
附:
charAt方法:
// Returns the char value at the specified index.
// An index ranges from 0 to length() - 1.
// The first char value of the sequence is at index 0,
// the next at index 1, and so on, as for array indexing.
// If the char value specified by the index is a surrogate,
// the surrogate value is returned.
public char charAt(int index)
codePointAt方法:
// Returns the character (Unicode code point) at the specified index.
// The index refers to char values (Unicode code units) and ranges
// from 0 to length() - 1.
// If the char value specified at the given
// index is in the high-surrogate range, the following
// index is less than the length of this String,
// and the char value at the following index is in
// the low-surrogate range, then the supplementary code
// point corresponding to this surrogate pair is returned.
// Otherwise, the char value at the given index is returned.
public int codePointAt(int index)