当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java StringBuffer codePointAt()用法及代码示例


StringBuffer类的codePointAt()方法按StringBuffer包含的顺序在该索引处返回一个字符Unicode点。此方法返回该索引处字符的“Unicodenumber”。索引值必须介于0到length-1之间。
如果给定索引处的char值位于high-surrogate范围内,则下一个索引小于此序列的长度,并且后续索引处的char值位于low-surrogate范围内,则对应于此代理的补充代码点对返回。否则,将返回给定索引处的char值。

用法:

public int codePointAt(int index)

参数:此方法采用一个参数索引,该参数索引是int值,表示要返回其unicode值的字符的索引。


返回值:此方法返回指定索引处字符的unicode号。

异常:当index为负或大于或等于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)



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 StringBuffer codePointAt() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。