带有示例的Java中的 StringBuilder codePointCount()
StringBuilder 类的codePointBefore()方法返回StringBuilder 包含的String 中指定文本范围内Unicode 码点的个数。该方法以两个索引作为参数——第一个表示文本范围第一个字符的索引的开始索引和表示文本范围最后一个字符之后的索引的结束索引。索引指的是 char 值(Unicode 代码单元),索引的值必须介于 0 到 length-1 之间。文本范围从 beginIndex 开始并延伸到索引 endIndex – 1 处的字符。因此文本范围的长度(以字符为单位)为endIndex-beginIndex 。
句法:
public int
codePointCount(int beginIndex, int endIndex)
参数:该方法接受两个参数
- beginIndex:文本范围的第一个字符的索引。
- endIndex:文本范围最后一个字符之后的索引。
返回值:此方法返回指定文本范围内的 Unicode 代码点数。
异常:如果出现以下情况,此方法将引发IndexOutOfBoundsException :
- beginIndex 小于零,
- 或 endIndex 大于 String 的长度,
- 或 beginIndex 大于 endIndex。
下面的程序演示了 StringBuilder 类的 codePointCount() 方法:
示例 1:
// Java program to demonstrate
// the codePointCount() 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 = " + str.toString());
// returns the codepoint count from index 2 to 8
int codepoints = str.codePointCount(2, 8);
System.out.println("No of Unicode code points = "
+ codepoints);
}
}
输出:
String = WelcomeGeeks
No of Unicode code points = 6
示例 2:
// Java program to demonstrate
// the codePointCount() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder
str
= new StringBuilder("GeeksForGeeks");
// print string
System.out.println("String = "
+ str.toString());
// returns the codepoint count
// from index 3 to 7
int
codepoints
= str.codePointCount(3, 7);
System.out.println("No of Unicode code points"
+ " between index 3 and 7 = "
+ codepoints);
}
}
输出:
String = GeeksForGeeks
No of Unicode code points between index 3 and 7 = 4
示例 3:演示 IndexOutOfBoundsException
// Java program to demonstrate
// exception thrown by the codePointCount() Method.
class GFG {
public static void main(String[] args)
{
// create a StringBuilder object
// with a String pass as parameter
StringBuilder
str
= new StringBuilder("GeeksForGeeks");
try {
// make beginIndex greater than endIndex
int codepoints = str.codePointCount(7, 4);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Exception: java.lang.IndexOutOfBoundsException
参考:
https://docs.oracle.com/javase/10/docs/api/java Java, int)