1 取字符串的前i个字符 str=str.substring(0,i); 2 去掉字符串的前i个字符 str=str.substring(i); 3 从右边开始取i个字符 str=str.substring(str.length()-i); str=str.substring(str.length()-i,str.length()); 4 从右边开始去掉i个字符 str=str.substring(0,str.Length-i); 5 从开始截取到中间某个指定字符 midChar (该字符出现的第一次) str=str.substring(0,str.indexOf(midChar)); 6 从开始截取到指定某段字符串结尾 midStr str=str.substring(0,str.indexOf(midStr)+midStr.length()); 7 如果字符串中有"abc"则替换成"ABC" str=str.replace("abc","ABC");
如:
public class Test { public static void main(String[] args) { String str = "abcde12345MNBVC*()&%"; //截取字符串前5位 String substring1= str.substring(0,5); //截掉字符串前5位 String substring2 = str.substring(5); //截取字符串后5位 String substring3 = str.substring(str.length()-5); String substring4 = str.substring(str.length()-5,str.length()); //截掉字符串后5位 String substring5 = str.substring(0,str.length()-5); //截去字符串从第6位到第9位的字符串(从0 开始) String substring6 = str.substring(6,10); //将字符串abcde 替换成ABCDE String string6 =str.replace("abcde","ABCDE"); //从开始截取到指定字符5 (该字符出现的第一次) String midChar = "5"; String substring7 = str.substring(0,str.indexOf(midChar)+ midChar.length()); //从开始截取到指定字符串BVC String midStr ="BVC"; String substring8 = str.substring(0,str.indexOf(midStr )+midStr.length()); System.out.println(substring1); System.out.println(substring2); System.out.println(substring3); System.out.println(substring4); System.out.println(substring5); System.out.println(substring6); System.out.println(string6); System.out.println(substring7); System.out.println(substring8); } } 结果: abcde 12345MNBVC*()&% *()&% *()&% abcde12345MNBVC 2345 ABCDE12345MNBVC*()&% abcde12345 abcde12345MNBVC