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)
相關用法
- Java StringBuffer codePointBefore()用法及代碼示例
- Java StringBuilder delete()用法及代碼示例
- Java StringBuilder setLength()用法及代碼示例
- Java StringBuilder charAt()用法及代碼示例
- Java StringBuilder subSequence()用法及代碼示例
- Java StringBuilder codePointCount()用法及代碼示例
- Java StringBuilder replace()用法及代碼示例
- Java StringBuilder setCharAt()用法及代碼示例
- Java StringBuilder reverse()用法及代碼示例
- Java StringBuilder length()用法及代碼示例
- Java StringBuilder Class用法及代碼示例
- Java StringBuilder capacity()用法及代碼示例
- Java StringBuilder codePointAt()用法及代碼示例
- Java StringBuilder deleteCharAt()用法及代碼示例
- Java StringBuilder getChars()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 StringBuilder codePointBefore() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。