【轉載】Java 從原字串中擷取一個新的字串 subString()
阿新 • • 發佈:2018-11-10
substring
public String substring(int beginIndex)
-
返回一個新的字串,它是此字串的一個子字串。該子字串從指定索引處的字元開始,直到此字串末尾。
示例:
"unhappy".substring(2) returns "happy" "Harbison".substring(3) returns "bison" "emptiness".substring(9) returns "" (an empty string)
-
- 引數:
-
beginIndex
- 起始索引(包括)。 - 返回:
- 指定的子字串。
- 丟擲:
-
IndexOutOfBoundsException
- 如果beginIndex
為負或大於此String
物件的長度。
substring
public String substring(int beginIndex,int endIndex)
-
返回一個新字串,它是此字串的一個子字串。該子字串從指定的
beginIndex
endIndex - 1
處的字元。因此,該子字串的長度為endIndex-beginIndex
。示例:
"hamburger".substring(4, 8) returns "urge" "smiles".substring(1, 5) returns "mile"
-
- 引數:
-
beginIndex
- 起始索引(包括)。 -
endIndex
- 結束索引(不包括)。 - 返回:
- 指定的子字串。
- 丟擲:
-
IndexOutOfBoundsException
- 如果beginIndex
為負,或endIndex
大於此String
物件的長度,或beginIndex
大於endIndex
。
例項:
public class SubString { public static void main(String[] args) { String s1 = "I love cjj"; String s2; String s3; //返回一個新的字串,它是此字串的一個子字串。 //該子字串從指定索引處的字元開始,直到此字串末尾。 s2 = s1.substring(6); System.out.println(s2); //返回一個新字串,它是此字串的一個子字串。 //該子字串從指定的 beginIndex 處開始,直到索引 endIndex - 1 處的字元。 //因此,該子字串的長度為 endIndex-beginIndex s3 = s1.substring(1,6); System.out.println(s3); } }