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


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


StringBuffer类的offsetByCodePoints()方法返回StringBuffer包含的此String中的索引,该索引与codePointOffset代码点作为参数传递的索引偏移。未配对的替代项位于index和codePointOffset计数之间,每个代表一个代码点。

用法:

public int offsetByCodePoints(int index,
                       int codePointOffset)

参数:此方法有两个参数:


  • index:要偏移的索引
  • codePointOffset:代码点的偏移量

返回值:此方法返回此序列内的索引。

异常:如果以下任何一项为真,则此方法将引发IndexOutOfBoundsException:

  • 序列的索引长度。
  • codePointOffset> 0,以index开头的子序列少于codePointOffset代码点
  • codePointOffset

下面的程序演示StringBuffer类的offsetByCodePoints()方法:

示例1:

// Java program to demonstrate 
// the offsetByCodePoints() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuffer object 
        // with a String pass as parameter 
        StringBuffer 
            str 
            = new StringBuffer("WelcomeGeeks"); 
  
        // print string 
        System.out.println("String = "
                           + str.toString()); 
  
        // returns the index within this sequence 
        int returnvalue = str.offsetByCodePoints(1, 4); 
  
        // prints the index 
        System.out.println("Index = " + returnvalue); 
    } 
}
输出:
String = WelcomeGeeks
Index = 5

示例2:

// Java program to demonstrate 
// the offsetByCodePoints() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuffer object 
        // with a String pass as parameter 
        StringBuffer 
            str 
            = new StringBuffer("India Is great"); 
  
        // print string 
        System.out.println("String = " + str.toString()); 
  
        // returns the index within this sequence 
        int returnvalue = str.offsetByCodePoints(2, 9); 
  
        // prints the index 
        System.out.println("Index = " + returnvalue); 
    } 
}
输出:
String = India Is great
Index = 11

示例3:演示IndexOutOfBoundException

// Java program to demonstrate 
// Exception thrown by offsetByCodePoints() Method. 
  
class GFG { 
    public static void main(String[] args) 
    { 
  
        // create a StringBuffer object 
        // with a String pass as parameter 
        StringBuffer 
            str 
            = new StringBuffer("India"); 
  
        try { 
  
            // returns the index within this sequence 
            int returnvalue = str.offsetByCodePoints(2, 9); 
  
            // prints the index 
            System.out.println("Index = " + returnvalue); 
        } 
  
        catch (IndexOutOfBoundsException e) { 
            System.out.println("Exception: " + e); 
        } 
    } 
}
输出:
Exception: java.lang.IndexOutOfBoundsException

参考:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuffer.html#offsetByCodePoints(int, int)



相关用法


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