当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java StringBuffer codePointBefore()用法及代码示例


StringBuffer类的codePointBefore()方法是用于将索引作为参数并返回该索引之前存在的字符的“Unicode number”的方法。 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/lang/StringBuffer.html#codePointBefore(int)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuffer codePointBefore() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。