Java StringBuilder codePointBefore()方法及示例

Java StringBuilder codePointBefore()方法及示例

StringBuilder类codePointBefore() 方法以一个索引为参数,返回StringBuilder所包含的String中指定索引之前的字符的 “Unicode编号”。索引指的是char值(Unicode代码单位),索引的值必须在0到length-1之间。如果(index – 1)处的char值在低代用范围内,(index – 2)处的char值不是负值,且在高代用范围内,那么该方法将返回代用对的补充码位值。如果在索引-1处的char值是一个未配对的低代用品或高代用品,则返回代用品的值。

语法

public int codePointBefore(int index)

参数: 该方法接受一个int类型的参数 index ,代表要返回的unicode值后面的字符的索引。
返回值: 该方法返回给定索引前的字符的 “unicode数 “。
异常: 当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 length + 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/lang/StringBuilder.html#codePointBefore(int)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程