Java StringBuffer offsetByCodePoints()方法及实例
StringBuffer类 的 offsetByCodePoints() 方法返回StringBuffer包含的索引,该索引与作为参数传递的codePointOffset代码点相抵。位于索引和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/lang/StringBuffer.html#offsetByCodePoints(int, int)。