如何在 Java 中使用 java.lang.String 類的 substring() 方法?
substring() 方法返回一個 String 資料型別,它對應於原始字串從起始索引到結束索引的部分。如果未指定結束索引,則endIndex必須為字串長度。由於我們正在處理字串,因此索引從'0'位置開始。
語法
public String substring(int beginIndex) public String substring(int beginIndex, int endIndex)
beginIndex:我們想要開始剪下或擷取字串的起始索引或位置。
endIndex: 我們想要結束剪下或擷取字串的結束索引或位置。
此方法返回 String 資料型別,它對應於我們剪下的字串部分。如果未指定endIndex,則假定結束索引為字串長度 -1,如果beginIndex為負數或大於字串長度,則會丟擲IndexOutOfBoundsException。
示例
public class StringSubstringTest{ public static void main(String[] args) { String str = "Welcome to Tutorials Point"; System.out.println(str.substring(5)); System.out.println(str.substring(2, 5)); str.substring(6); System.out.println("str value: "+ str); String str1 = str.substring(5); System.out.println("str1 value: "+ str1); } }
輸出
me to Tutorials Point lco str value: Welcome to Tutorials Point str1 value: me to Tutorials Point
廣告