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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。