一:public String substring(int beginIndex)
返回一个新的字符串,它是此字符串的一个子字符串。
该子字符串从指定索引处的字符开始,直到此字符串末尾。
public class Test {
public static void main(String[] args) {
String str="Hello";
String subStr=str.substring(1);
System.out.println(subStr);
}
}
输出:ello
注:如果字符串中含有空格,也算一个位置的
public class Test {
public static void main(String[] args) {
String str=" Hello";
String subStr=str.substring(1);
System.out.println(subStr);
}
}
输出:Hello
二:public String substring(int beginIndex, int endIndex)
返回一个新字符串,它是此字符串的一个子字符串。
该子字符串从指定的 beginIndex
处开始,直到索引 endIndex - 1
处的字符。
该子字符串的长度为 endIndex-beginIndex.
注:substring(a,b)。a可以从索引0开始到b,但得出的子字符串不包括b索引代表的字符。
public class Test {
public static void main(String[] args) {
String str="Hello";
//最后一个索引是4
String subStr1=str.substring(0,4);
System.out.println(subStr1);
// substring(int beginIndex, int endIndex)
//要想得到最后一个字符串,让endIndex+1
String subStr2=str.substring(0,5);
System.out.println(subStr2);
}
}
输出:Hell
Hello