📜  Java中的 StringBuilder offsetByCodePoints() 方法及示例

📅  最后修改于: 2022-05-13 01:54:45.262000             🧑  作者: Mango

Java中的 StringBuilder offsetByCodePoints() 方法及示例

StringBuilder 类offsetByCodePoints()方法返回 StringBuilder 包含的此字符串中的索引,该索引与 codePointOffset 代码点作为参数传递的索引的偏移量。未配对的代理位于 index 和 codePointOffset 之间,每个都算作一个代码点。

句法:

public int offsetByCodePoints(int index,
                       int codePointOffset)

参数:此方法有两个参数:

  • index : 要偏移的索引
  • codePointOffset :代码点的偏移量

返回值:此方法返回此序列中的索引

异常:如果以下任何一项为真,则此方法抛出IndexOutOfBoundsException

  • index < 0 或 index > 序列的长度。
  • codePointOffset > 0 并且以 index 开头的子序列的代码点少于 codePointOffset
  • codePointOffset < 并且 index 之前的子序列小于 codePointOffset 代码点的绝对值。

下面的程序演示了 StringBuilder 类的 offsetByCodePoints() 方法:

示例 1:

// Java program to demonstrate
// the offsetByCodePoints() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder
            str
            = new StringBuilder("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 StringBuilder object
        // with a String pass as parameter
        StringBuilder
            str
            = new StringBuilder("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 StringBuilder object
        // with a String pass as parameter
        StringBuilder
            str
            = new StringBuilder("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)