Java源码___String类(三)

本文介绍了Java中String类的几个重要方法:codePointBefore用于获取指定位置前一个字符的Unicode值;codePointCount统计指定范围内的Unicode代码点数量;offsetByCodePoints计算基于当前位置偏移特定代码点数后的新位置;getChars实现字符数组与String间的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java.lang.String分析摘要:
<1>codePointBefore()
<2>codePointCount(int beginIndex, int endIndex)
<3>offsetByCodePoints(int index, int codePointOffset)
<4>getChar重载方法

1.codePointBefore()
 该方法返回某个指定的位置的前一位char字符的Unicode的解码值。

public int codePointBefore(int index) {
    int i = index - 1;
    //判断是下标是否越界
    if ((i < 0) || (i >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return Character.codePointBeforeImpl(value, index, 0);
}

这个方法是的属性有:public公有的。
返回值:int
返回值说明:char字符的Unicode的解码值

该方法的主要作用是:返回指定位置的char字符的前一位字符的Unixode的解码值。
 
2. codePointCount(int beginIndex, int endIndex)
 该方法返回指定字符串下标之间的Unicode代码点的个数。

public int codePointCount(int beginIndex, int endIndex) {
   if (beginIndex < 0 || endIndex > value.length || beginIndex > endIndex) {
       throw new IndexOutOfBoundsException();
   }
  return Character.codePointCountImpl(value, beginIndex, endIndex - beginIndex);
}

这个方法是的属性有:public公有。
返回值:int
返回值说明:返回给定坐标之间的的字符串的Unicode解码数量。

该方法的主要作用是:因为某些字符可能是由两个char组成,所以用这个方法才是真实的测量解码数量。
 

3.offsetByCodePoints(int index, int codePointOffset)

//index:下标位置
//codePointOffset:偏移数量
public int offsetByCodePoints(int index, int codePointOffset) {
    //这边有点不理解,index如果是下标的话,取值到value.length应该报错
    //但是这边却可以取值到value.length
    if (index < 0 || index > value.length) {
        throw new IndexOutOfBoundsException();
    }
    return Character.offsetByCodePointsImpl(value, 0, value.length,
            index, codePointOffset);
}

这个方法是的属性有:public公有
返回值:int
返回值说明:返回index位置开始,偏移codePointOffset后的下标位置

该方法的主要作用是:这个方法貌似返回的是index位置开始后,偏移codePointOffset后的下标位置。
 

4. getChars重载方法

//默认包权限,我们基本上用不了这个方法
void getChars(char dst[], int dstBegin) {
    System.arraycopy(value, 0, dst, dstBegin, value.length);
}

//将目标字符串从下标srcBegin开始到srcEnd(不包括),替换dest[]从下标位置destBegin开始
//srcBegin:要复制的字符串的开始下标
//srcEnd:要复制的字符串的结束下标+1
//dest[]:要被替换的char数组
//destBegin:要被替换的char数组的开始下标
public void getChars(int srcBegin, int srcEnd, char dst[], int dstBegin) {
   if (srcBegin < 0) {
        throw new StringIndexOutOfBoundsException(srcBegin);
    }
    if (srcEnd > value.length) {
        throw new StringIndexOutOfBoundsException(srcEnd);
    }
    if (srcBegin > srcEnd) {
        throw new StringIndexOutOfBoundsException(srcEnd - srcBegin);
    }
    System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
}

该方法的主要作用是:将字符串的srcBegin到(srcEnd-1)位置的char字符代替char数组dest,并且替换的位置在从destBegin开始。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值