Java StringBuffer codePointBefore()方法及示例

来源:这里教程网 时间:2026-02-17 21:13:36 作者:

Java StringBuffer codePointBefore()方法及示例

StringBuffer类的 codePointBefore() 方法是一个以索引为参数的方法,用于返回该索引前的字符的 “Unicode号码”。索引的值必须在0到length-1之间。

如果(index – 1)处的char值在低代理范围内,(index – 2)处的char值不是负值,且在高代理范围内,那么代理对的补充码位值将由方法返回。如果在索引-1处的char值是一个未配对的低代用品或高代用品,则返回代用品的值。

语法

public int codePointBefore(int index)

参数: 该方法有一个参数 index ,它是要返回unicode值的字符后面的字符的索引。

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

异常: 当索引为负数或大于等于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/lang/StringBuffer.html#codePointBefore(int)

相关推荐