📜  Java中的 StringBuilder codePointBefore() 示例

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

Java中的 StringBuilder codePointBefore() 示例

StringBuilder类codePointBefore()方法以索引为参数,返回StringBuilder所包含的String中指定索引之前字符的“Unicode编号”。 index 指的是 char 值(Unicode 代码单元),index 的值必须介于 0 到 length-1 之间。

如果 (index – 1) 处的 char 值在低代理范围内,并且 (index – 2) 处的 char 不为负且值在高代理范围内,则返回代理对的补充代码点值通过方法。如果索引 - 1 处的 char 值是未配对的低代理或高代理,则返回代理值。

句法:

public int codePointBefore(int index)

参数:该方法接受一个int类型参数index表示要返回其unicode值的字符后面的字符的索引。

返回值:此方法返回给定索引之前字符的“unicode number”

异常:当 index 为负数或大于或等于 length() 时,此方法抛出IndexOutOfBoundsException

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

示例 1:

// Java program to demonstrate
// the codePointBefore() 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 is "
                           + str.toString());
  
        // get unicode of char at index 1
        // using codePointBefore() method
        int unicode = str.codePointBefore(2);
  
        // print char and Unicode
        System.out.println("Unicode of character"
                           + " at position 1 = " + unicode);
  
        // get unicode of char at index 10
        // using codePointBefore() method
        unicode = str.codePointBefore(11);
  
        // print char and Unicode
        System.out.println("Unicode of character"
                           + " at position 10 = "
                           + unicode);
    }
}
输出:
String is WelcomeGeeks
Unicode of character at position 1 = 101
Unicode of character at position 10 = 107

示例 2:演示 IndexOutOfBoundsException

// Java program to demonstrate
// exception thrown by codePointBefore() Method.
  
class GFG {
    public static void main(String[] args)
    {
        // create a StringBuilder object
        // with a String pass as parameter
        StringBuilder
            str
            = new StringBuilder("WelcomeGeeks");
  
        try {
  
            // get unicode of char at position 1ength + 2
            int unicode = str.codePointBefore(
                str.length() + 2);
        }
  
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}
输出:
Exception: java.lang.StringIndexOutOfBoundsException:
 String index out of range: 14

参考:
https://docs.oracle.com/javase/10/docs/api/java Java)