1. 程式人生 > >【轉載】Java 從原字串中擷取一個新的字串 subString()

【轉載】Java 從原字串中擷取一個新的字串 subString()

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);
    }
}
複製程式碼