Java StringBuffer subSequence()方法及实例

Java StringBuffer subSequence()方法及实例

StringBuffer类的 subSequence(int start, int end) 方法是一个内置的方法,用于返回 位于该序列的索引开始和结束-1之间的 字符的子序列 。该子序列以索引开始处的字符值开始,以(end-1)处的字符值结束。返回的子序列的长度是end-start。因此,如果start等于end,那么将返回一个空的子序列。

语法

public CharSequence subSequence?(int start, int end)

参数:

该方法接受两个参数。

  1. start 是整数类型的值,指的是子序列的起始索引。
  2. end 是整数类型的值,指的是子序列的最后索引。

返回:

该方法返回start到end-1范围内的指定子序列。

异常:

如果start或end为负数,如果end大于length(),或者start大于end,则抛出 IndexOutOfBoundsException

以下程序说明了java.lang.StringBuffer.subSequence()方法:

示例1 :

// Java program to demonstrate
// the subSequence() 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 contains = " + str);
 
        // get subSequence between index 0 to 7
        // using subSequence() and print
        System.out.println("SubSequence = "
                           + str.subSequence(0, 7));
    }
}

输出

String length = 12 and contains = WelcomeGeeks
SubSequence = Welcome

例2 :

// Java program to demonstrate
// the subSequence() Method.
 
class GFG {
 
    public static void main(String[] args)
    {
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("Indian Team Played Well");
 
        // print string
        System.out.println("String contains = " + str);
 
        // get subSequence between index 0 to 7
        // using subSequence() and print
        System.out.println("SubSequence = "
                           + str.subSequence(7, 18));
    }
}

输出

String contains = Indian Team Played Well
SubSequence = Team Played

例3: 当开始>结束。

// Java program to demonstrate
// Exception thrown by the subSequence() Method.
 
class GFG {
 
    public static void main(String[] args)
    {
        // create a StringBuffer object
        // with a String pass as parameter
        StringBuffer str
            = new StringBuffer("Indian Team Played Well");
 
        try {
            // get subSequence between index 0 to 7
            // using subSequence() and print
            System.out.println(str.subSequence(19, 18));
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
}

输出

java.lang.StringIndexOutOfBoundsException: String index out of range: -1
    at java.lang.AbstractStringBuffer.substring(AbstractStringBuffer.java:935)
    at java.lang.StringBuffer.substring(StringBuffer.java:76)
    at java.lang.AbstractStringBuffer.subSequence(AbstractStringBuffer.java:912)
    at java.lang.StringBuffer.subSequence(StringBuffer.java:76)
    at GFG.main(File.java:16)

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程