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