Java StringBuffer codePointAt()方法及示例
StringBuffer类 的 codePointAt() 方法返回StringBuffer包含的序列中该索引处的字符Unicode点。该方法返回该索引处的字符的 “Unicodenumber”。
如果在给定索引处的字符值在高代用范围内,下面的索引小于这个序列的长度,并且下面的索引处的字符值在低代用范围内,那么将返回这个代用对对应的补充码。否则,将返回给定索引处的char值。
语法
public int codePointAt(int index)
参数: 该方法需要一个参数 index ,该参数为int值,代表要返回unicode值的字符的索引。
返回值: 该方法返回指定索引处的字符的 unicode编号 。
异常: 当索引为负数或大于等于length()时,该方法会产生IndexOutOfBoundsException。
下面的程序演示了StringBuffer类的codePointAt()方法。
例1 :
// Java program to demonstrate// the codePointAt() method class GFG { public static void main(String[] args) { // create a StringBuffer object StringBuffer str = new StringBuffer(); // add the String to StringBuffer Object str.append("Geeksforgeeks"); // get unicode of char at position 10 int unicode = str.codePointAt(10); // print the result System.out.println("Unicode of Character " + "at Position 10 " + "in StringBuffer = " + unicode); }}
输出:
Unicode of Character at Position 10 in StringBuffer = 101
例2: 演示IndexOutOfBoundsException
// Java program demonstrate// IndexOutOfBoundsException thrown by// the codePointAt() 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"); try { // get char at position 25 which is // greater then length int i = str.codePointAt(25); } catch (IndexOutOfBoundsException e) { System.out.println("Exception: " + e); } }}
输出:
Exception: java.lang.StringIndexOutOfBoundsException: String index out of range: 25
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#codePointAt(int)
