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


Java StringBuilder codePointBefore()用法及代碼示例


StringBuilder類的codePointBefore()方法將索引作為參數,並返回StringBuilder包含的String中指定索引之前的字符的“Unicode number”。索引引用char值(Unicode代碼單位),並且索引的值必須介於0到length-1之間。

如果(index-1)處的char值在低代理範圍內,(index-2)處的char不為負且值在高代理範圍內,則返回代理對的補充代碼點值通過方法。如果索引-1處的char值是未配對的低代理或高代理,則返回代理值。

用法:


public int codePointBefore(int index)

參數:此方法接受一個int型參數索引,該索引表示要返回其unicode值的字符之後的字符的索引。

返回值:此方法返回給定索引之前的字符的“unicode number”。

異常:當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 1ength + 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)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuilder codePointBefore() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。