Java.lang.String.subSequence()是Java中的内置函数,该函数返回CharSequence。 CharSequence,它是此序列的子序列。子序列以指定索引处的char值开始,并以(end-1)处的char值结束。返回序列的长度(以字符为单位)为(end-start,因此,如果start == end,则返回一个空序列。
用法:
public CharSequence subSequence(int start, int end) 参数: 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)
相关用法
- Java ZoneOffset of(String)用法及代码示例
- Java String toString()用法及代码示例
- Java PrintWriter println(String)用法及代码示例
- Java StringWriter write(String, int, int)用法及代码示例
- Java StringWriter write(String)用法及代码示例
- Java DecimalFormatSymbols setCurrencySymbol(String)用法及代码示例
- Java PrintWriter print(String)用法及代码示例
- Java Matcher quoteReplacement(String)用法及代码示例
- Java Writer write(String)用法及代码示例
- Java Matcher group(String)用法及代码示例
- Java Writer write(String, int, int)用法及代码示例
- Java PrintStream println(String)用法及代码示例
- Java PrintStream print(String)用法及代码示例
- Java Matcher start(String)用法及代码示例
注:本文由纯净天空筛选整理自ChetnaAgarwal大神的英文原创作品 Java String subSequence() method with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。