面试官:String类的charAt方法返回值是什么?
侯选人:返回的是string类中对应位置的字符unicode值。
面试官:错,pass了。
首选Java中String类是以UTF-16编码来存储的,我们定义一个字符串,这个字段串会先用
UTF-16进行编码,编码之后的值以char数组的形式存储在String类的value属性里。
在维基百科中,UTF-16编码的定义如下:
UTF-16是Unicode字符编码五层次模型的第三层:字符编码表(Character Encoding Form,也称为"storage format")的一种实现方式。即把Unicode字符集的抽象码位映射为16位长的整数(即码元)的序列,用于数据存储或传递。Unicode字符的码位,需要1个或者2个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)