offsetByCodePoints()与codePointAt()
来源:互联网 发布:知乎rss订阅地址 编辑:程序博客网 时间:2024/05/29 05:15
在Java api文档中对这两个方法的解释为
offsetByCodePointspublic int offsetByCodePoints(int index, int codePointOffset)返回此 String 中从给定的 index 处偏移 codePointOffset 个代码点的索引。文本范围内由 index 和 codePointOffset 给定的未配对代理项各计为一个代码点。参数:index - 要偏移的索引codePointOffset - 代码点中的偏移量返回:String 的索引抛出:IndexOutOfBoundsException - 如果 index 为负或大于此 String 的长度;或者 codePointOffset 为正,且以 index 开头子字符串的代码点比 codePointOffset 少;如果 codePointOffset 为负,且 index 前面子字符串的代码点比 codePointOffset 的绝对值少。
这里的index就是你指定的任意第 i 个码点,假如你想知道距离第 i 个码点 x 个码点(x可正可负)是 相对于第0个码点第几个码点,则可以用offsetByCodePoints( i , x )得到的你想要的值。比方说
String astring = "abcdABCD";int cpcount = astring.offsetByCodePoints(7,-4)cpcount的值应该是3(即表示d距离a 3个码点,也就是距离第0个位置3个位置);
codePointAtpublic int codePointAt(int index)返回指定索引处的字符(Unicode 代码点)。索引引用 char 值(Unicode 代码单元),其范围从 0 到 length() - 1。如果给定索引指定的 char 值属于高代理项范围,则后续索引小于此 String 的长度;如果后续索引处的 char 值属于低代理项范围,则返回该代理项对相应的增补代码点。否则,返回给定索引处的 char 值。参数:index - char 值的索引返回:index 处字符的代码点值抛出:IndexOutOfBoundsException - 如果 index 参数为负或小于此字符串的长度。还是以上面那个例子,d距离a,有3个位置,这个3通过offsetByCodePoints()得到,并且就可以看成是一个索引值,通过他你就能找到对应位置上是d
String astring = "abcdABCD";int cpcount = astring.offsetByCodePoints(7,-4)int dddunicode = atest.codePointAt(cpcount);dddunicode = 100;这个其实是ASCII码值
为了更好地理解这两个方法,下面再举例:
public class Program2 {public static void main(String[] args){String atest = "abcABCa";if(atest.equals("abcABCa")){int cp1 = atest.offsetByCodePoints(0,0);int cp4 = atest.offsetByCodePoints(0, 3);int cp7 = atest.offsetByCodePoints(0, 6);System.out.println("cp1 is "+cp1+" cp2 is "+ cp4+" cp7 is "+cp7);int cp1unicode = atest.codePointAt(cp1);int cp4unicode = atest.codePointAt(cp4);int cp7unicode = atest.codePointAt(cp7);System.out.println(cp1unicode+" "+cp4unicode+" "+cp7unicode);}}}结果是:
cp1 is 0 cp2 is 3 cp7 is 697 65 97
阅读全文
0 0
- offsetByCodePoints()与codePointAt()
- java offsetByCodePoints()的用法
- String类的codePointAt()方法
- String类常用方法之charAt()、codePointAt()示例
- String类常用方法之charAt()、codePointAt()示例
- ES6-字符串的扩展-codePointAt()和String.fromCodePoint()
- codePointAt方法——获取字符数组元素的代码点
- 与
- 与
- “” 与 “”
- ##与#
- >> 与 > >
- :与::
- &与&&
- && 与 &
- [[与((
- >>与>>>
- *与++
- 数组中第K大的数
- 给定整数序列求连续子串最大和
- Java/Android 设计模式系列(8)--桥接模式
- 设计模式_单例模式(5)
- ActiveMQ三机器高可用-负载均衡集群
- offsetByCodePoints()与codePointAt()
- PAT 甲级 1019. General Palindromic Number
- MyBatis动态传入表名,字段名参数的解决办法--用于分表--表名是动态的
- Flask-RESTful接口开发学习笔记一:实现简单的GET请求
- 单一职责原则
- 2017理数全国卷I T21
- C++ 域名转IP地址
- C# winform PictureBox插入图片并设置自适应显示
- 双边滤波原理理解