Java StringBuilder subSequence()方法及示例
StringBuilder类的 subSequence(int start, int end) 方法是一个内置的方法,用于 返回 位于该序列的索引开始和结束-1之间的 字符的子序列 。该子序列以索引开始处的字符值开始,以(end-1)处的字符值结束。返回的子序列的长度是end-start。因此,如果start等于end,那么将返回一个空的子序列。
语法
public CharSequence subSequence?(int start, int end)
参数:
该方法接受两个参数。
- start 是整数类型的值,指的是子序列的起始索引。
- end 是整数类型的值,指的是子序列的最后索引。
返回:
该方法返回start到end-1范围内的指定子序列。
异常:
如果start或end为负数,如果end大于length(),或者start大于end,则抛出 IndexOutOfBoundsException 。
以下程序说明了java.lang.StringBuilder.subSequence()方法:
示例1 :
// Java program to demonstrate
// the subSequence() 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 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 StringBuilder object
// with a String pass as parameter
StringBuilder str
= new StringBuilder("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 StringBuilder object
// with a String pass as parameter
StringBuilder str
= new StringBuilder("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.AbstractStringBuilder.substring(AbstractStringBuilder.java:935)
at java.lang.StringBuilder.substring(StringBuilder.java:76)
at java.lang.AbstractStringBuilder.subSequence(AbstractStringBuilder.java:912)
at java.lang.StringBuilder.subSequence(StringBuilder.java:76)
at GFG.main(File.java:16)
参考文献:
https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#subSequence(int, int)