一、字符串替换
1、replace方法
该方法的作用是替换字符串中所有指定的字符,然后生成一个新的字符串。经过该方法调用以后,原来的字符串不发生改变。例如:
String s = “dudaduda”; String s1 = s.replace(‘a’,‘1’); |
2、replaceAll方法
该代码的作用是将字符串s中所有的字符a替换成字符1,生成的新字符串s1的值是“dud1dud1”,而字符串s的内容不发生改变。
如果需要将字符串中某个指定的字符串替换为其它字符串,则可以使用replaceAll方法,例如:
String s = “didadida”; String s1 = s.replaceAll(“da”,“12”); |
该代码的作用是将字符串s中所有的字符串“da”替换为“12”,生成新的字符串“di12di12”,而字符串s的内容也不发生改变。
3、replaceFirst方法
如果只需要替换第一个出现的指定字符串时,可以使用replaceFirst方法,例如:
String s = “didadida”; String s1 = s. replaceFirst (“da”,“12”); |
该代码的作用是只将字符串s中第一次出现的字符串“da”替换为字符串“12”,则字符串s1的值是“di12dida”,字符串s的内容也不发生改变。
二、字符串截取
1、String.substring(int start)
参数:
start:要截取位置的索引
返回:
从start开始到结束的字符串
例如:String str = "hello word!";
System.out.println(str.substring(1));
System.out.println(str.substring(3));
System.out.println(str.substring(6));
将得到结果为:
ello word!
lo word!
ord!
如果start大于字符串的长度将会抛出越界异常;
2、String.substring(int beginIndex, int endIndex)
参数:
beginIndex 开始位置索引
endIndex 结束位置索引
返回:
从beginIndex位置到endIndex位置内的字符串,不包含endIndex。
例如:String str = "hello word!";
System.out.println(str.substring(1,4));
System.out.println(str.substring(3,5));
System.out.println(str.substring(0,4));
将得到结果为:
ell
lo
hell
如果startIndex和endIndex其中有越界的将会抛出越界异常。