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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。