网站首页 > java教程 正文
面试官: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)
猜你喜欢
- 2024-11-09 为什么Java中的String是不可变的(Immutable)
- 2024-11-09 java之学习int和String的相互转换
- 2024-11-09 吃透Java基础十三:String字符串(java string字符集)
- 2024-11-09 初学者参考:C#编程中byte数组转为16进制表示的字符串
- 2024-11-09 没想到,一个小小的String还有这么多窍门
- 2024-11-09 如何在 Bash 中将字符串拆分为数组?
- 2024-11-09 StringUtils字符串分割转数组(string分割成数组)
- 2024-11-09 手把手教你:C#如何将字符串列表转换为字节数组并写入文件!
- 2024-11-09 详解Java中的数据对象#数组#遍历数组#软件开发
- 2024-11-09 Java Map 所有的值转为String类型
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- java反编译工具 (77)
- java反射 (57)
- java接口 (61)
- java随机数 (63)
- java7下载 (59)
- java数据结构 (61)
- java 三目运算符 (65)
- java对象转map (63)
- Java继承 (69)
- java字符串替换 (60)
- 快速排序java (59)
- java并发编程 (58)
- java api文档 (60)
- centos安装java (57)
- java调用webservice接口 (61)
- java深拷贝 (61)
- 工厂模式java (59)
- java代理模式 (59)
- java.lang (57)
- java连接mysql数据库 (67)
- java重载 (68)
- java 循环语句 (66)
- java反序列化 (58)
- java时间函数 (60)
- java是值传递还是引用传递 (62)
本文暂时没有评论,来添加一个吧(●'◡'●)