📜  Java中的 StringBuffer codePointBefore() 方法及示例

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

Java中的 StringBuffer codePointBefore() 方法及示例

StringBuffer 类codePointBefore()方法是一种用于将索引作为参数并返回该索引之前存在的字符的“Unicode 编号”的方法。 index 的值必须介于 0 到 length-1 之间。

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

句法:

public int codePointBefore(int index)

参数:该方法采用一个参数索引,即要返回其unicode值的字符后面的字符的索引。

返回值:此方法返回给定索引之前字符的unicode 编号

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

下面的程序说明了 codePointBefore() 方法:

示例 1:

// Java program to demonstrate
// the codePointBefore() Method.
  
class GFG {
    public static void main(String[] args)
    {
  
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer
            str
            = new StringBuffer("GeeksForGeeks Contribute");
  
        // get unicode of char at index 13
        // using codePointBefore() method
        int unicode = str.codePointBefore(14);
  
        // print char and Unicode
        System.out.println("Unicode of character"
                           + " at position 13 = "
                           + unicode);
    }
}
输出:
Unicode of character at position 13 = 32

示例 2:演示 IndexOutOfBoundsException

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

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