Java中的 StringBuffer offsetByCodePoints() 方法及示例
StringBuffer 类的offsetByCodePoints()方法返回 StringBuffer 包含的此字符串中的索引,该索引与 codePointOffset 代码点作为参数传递的索引的偏移量。未配对的代理位于 index 和 codePointOffset 之间,每个都算作一个代码点。
句法:
public int offsetByCodePoints(int index,
int codePointOffset)
参数:此方法有两个参数:
- index : 要偏移的索引
- codePointOffset :代码点的偏移量
返回值:此方法返回此序列中的索引。
异常:如果以下任何一项为真,则此方法抛出IndexOutOfBoundsException :
- index < 0 或 index > 序列的长度。
- codePointOffset > 0 并且以 index 开头的子序列的代码点少于 codePointOffset
- codePointOffset < 并且 index 之前的子序列小于 codePointOffset 代码点的绝对值。
下面的程序演示了 StringBuffer 类的 offsetByCodePoints() 方法:
示例 1:
// Java program to demonstrate
// the offsetByCodePoints() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer
str
= new StringBuffer("WelcomeGeeks");
// print string
System.out.println("String = "
+ str.toString());
// returns the index within this sequence
int returnvalue = str.offsetByCodePoints(1, 4);
// prints the index
System.out.println("Index = " + returnvalue);
}
}
输出:
String = WelcomeGeeks
Index = 5
示例 2:
// Java program to demonstrate
// the offsetByCodePoints() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer
str
= new StringBuffer("India Is great");
// print string
System.out.println("String = " + str.toString());
// returns the index within this sequence
int returnvalue = str.offsetByCodePoints(2, 9);
// prints the index
System.out.println("Index = " + returnvalue);
}
}
输出:
String = India Is great
Index = 11
示例 3:演示 IndexOutOfBoundException
// Java program to demonstrate
// Exception thrown by offsetByCodePoints() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuffer object
// with a String pass as parameter
StringBuffer
str
= new StringBuffer("India");
try {
// returns the index within this sequence
int returnvalue = str.offsetByCodePoints(2, 9);
// prints the index
System.out.println("Index = " + returnvalue);
}
catch (IndexOutOfBoundsException e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Exception: java.lang.IndexOutOfBoundsException
参考:
https://docs.oracle.com/javase/10/docs/api/java Java, int)