substring() 方法返回字符串的子字符串。
語法:
public String substring(int beginIndex)
public String substring(int beginIndex, int endIndex)
參數:
- beginIndex -- 起始索引(包括), 索引從 0 開始。
- endIndex -- 結束索引(不包括)。
返回值
子字符串。
例子
String str = "Hello World!";
//截取str子串,從下標為6(包括6)到字符串結束
System.out.println(str.substring(6)); //World!
//截取str子串,從下標為0(包括0)到下標為5(不包括5)
System.out.println(str.substring(0, 5)); //Hello
以下是相當於從頭到尾截取字符串 :
String str = "Hello World!";
//Call to 'substring(0)' is redundant(多余的)
System.out.println(str.substring(0)); //Hello World!
//Call to 'substring(0, str.length())' is redundant(多余的)
System.out.println(str.substring(0, str.length())); //Hello World!