當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。