str=str.substring(int beginIndex);截取掉str從首字母起長度為beginIndex的字串,將剩餘字串賦值給str;
str=str.substring(int beginIndex,int endIndex);截取str中從beginIndex開始至endIndex結束時的字串,並將其賦值給str;
執行個體
public class Utils {
public static String diff(String str1, String str2) {
int index = str1.lastIndexOf(str2);
if (index > -1) {
return str1.substring(str2.length());
}
return str1;
}
}
執行個體二
public class TestSubstring {
public static void main(String[] args) {
String str1 = "fghjkl";
String str2 = str1.substring(1);//從第1號位置開始截取字串,截到最後,把截取後的返回,賦值給str2
System.out.println("str1 == " + str1);
System.out.println("str2 == " + str2);
}
}
執行個體三
public static String substring(String str, int start, int end) {
if (str == null) {
return null;
}
// handle negatives
if (end < 0) {
end = str.length() + end; // remember end is negative
}
if (start < 0) {
start = str.length() + start; // remember start is negative
}
// check length next
if (end > str.length()) {
end = str.length();
}
// if start is greater than end, return ""
if (start > end) {
return "";
}
if (start < 0) {
start = 0;
}
if (end < 0) {
end = 0;
}
return str.substring(start, end);
}
}