Java StringBuilder codePointCount()方法及示例

Java StringBuilder codePointCount()方法及示例

StringBuilder类codePointBefore() 方法返回StringBuilder包含的String中指定文本范围内的Unicode代码点的数量。该方法需要两个索引作为参数–第一个是beginIndex,代表文本范围的第一个字符的索引,第二个是endIndex,代表文本范围的最后一个字符之后的索引。索引指的是char值(Unicode代码单位),索引的值必须在0到length-1之间。文本范围从beginIndex开始,延伸到endIndex-1的字符。因此,文本范围的长度(以字符为单位)为 endIndex-beginIndex。

语法

public int 
    codePointCount(int beginIndex, int endIndex)

参数: 该方法接受两个参数

  • beginIndex: 文本范围的第一个字符的索引。
  • endIndex: 文本范围的最后一个字符后的索引。

返回值: 该方法返回 指定文本范围内的Unicode代码点的数量

异常: 如果出现以下情况,该方法会抛出 IndexOutOfBoundsException

  • the 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/lang/StringBuilder.html#codePointCount(int, int)。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程