Java中的字符.offsetByCodePoints()方法
字符.offsetByCodePoints(CharSequence seq, int index, int codePointOffset)是Java中的一个内置方法,它返回给定 char 序列中的索引,该索引与给定索引偏移 codePointOffset 代码点。由 index 和 codePointOffset 给出的文本范围内的未配对代理分别计为一个代码点。
句法:
public static int offsetByCodePoints(CharSequence seq, int index, int codePointOffset)
参数:
- seq – 字符序列
- index – 要偏移的索引
- codePointOffset – 代码点的偏移量
返回值: 字符类的这个方法返回字符序列内的索引。
例外:
- NullPointerException – 如果 seq 为空。
- IndexOutOfBoundsException – 如果 index 为负数或大于 char 序列的长度,或者如果 codePointOffset 为正数并且以 index 开头的子序列的代码点少于 codePointOffset,或者如果 codePointOffset 为负数并且 index 之前的子序列的绝对值小于codePointOffset 代码点。
以下是说明上述方法的程序:
方案一:
// Code to illustrate the offsetByCodePoints() method
import java.lang.*;
public class gfg {
public static void main(String[] args)
{
// Create a CharSequence s and assign value
CharSequence s = "Hello World";
// Result of offsetByCodePoints on s
String str = "The index within the char sequence s is " +
Character.offsetByCodePoints(s, 2, 6);
// Print str value
System.out.println(str);
}
}
输出:
The index within the char sequence s is 8
方案二:
// Code to illustrate the offsetByCodePoints() method
import java.lang.*;
public class gfg {
public static void main(String[] args)
{
// Create a CharSequence s and assign value
CharSequence s = "geeks for geeks";
// Result of offsetByCodePoints on s
String str = "The index within the char sequence s is " +
Character.offsetByCodePoints(s, 3, 8);
// Print str value
System.out.println(str);
}
}
输出:
The index within the char sequence s is 11