Java String subSequence() 方法与示例
Java .lang.String.subSequence()是Java中的一个内置函数,它返回一个 CharSequence。 CharSequence 是此序列的子序列。子序列以指定索引处的 char 值开始,以 (end-1) 处的 char 值结束。返回序列的长度(以字符为单位)为 (end-start,因此如果 start == end 则返回一个空序列。
句法:
public CharSequence subSequence(int start, int end)
Parameters:
start - This is the index from where the subsequence starts, it is inclusive.
end - This is the index where the subsequence ends, it is exclusive.
回报:
它返回范围 [start, end) 中的指定子序列。
错误和异常:
IndexOutOfBoundsException – 如果 start 或 end 为负数,如果 end 大于 length(),或者 start 大于 end,则抛出此错误。
程序 1:展示Java.lang.String.subSequence()函数的工作原理。
// Java program to demonstrate working
// of Java.lang.String.subSequence() method
import java.lang.Math;
class Gfg {
// driver code
public static void main(String args[])
{
String Str = "Welcome to geeksforgeeks";
// prints the subsequence from 0-7, exclusive 7th index
System.out.print("Returns: ");
System.out.println(Str.subSequence(0, 7));
System.out.print("Returns: ");
System.out.println(Str.subSequence(10, 24));
}
}
输出:
Returns: Welcome
Returns: geeksforgeeks
程序 2:当索引为负时显示Java.lang.String.subSequence()函数的错误
// Java program to demonstrate error
// of Java.lang.String.subSequence() method
import java.lang.Math;
class Gfg {
// driver code
public static void main(String args[])
{
String Str = "Welcome to geeksforgeeks";
// throws an error as index is negative
System.out.print("Returns: ");
System.out.println(Str.subSequence(-1, 7));
}
}
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: -1
at java.lang.String.substring(String.java:1960)
at java.lang.String.subSequence(String.java:2003)
at Gfg.main(File.java:15)
程序 3:当索引超出范围时显示Java.lang.String.subSequence()函数的错误。
// Java program to demonstrate error
// of Java.lang.String.subSequence() method
import java.lang.Math;
class Gfg {
// driver code
public static void main(String args[])
{
String Str = "Welcome to geeksforgeeks";
// throws an error as end is out of range
System.out.print("Returns: ");
System.out.println(Str.subSequence(10, 50));
}
}
输出:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 50
at java.lang.String.substring(String.java:1963)
at java.lang.String.subSequence(String.java:2003)
at Gfg.main(File.java:16)