思路一:直接用字符串中的replaceAll()方法实现,关键在于字符串有replaceAll()方法,所以先转化为字符串
public class Solution {
public String replaceSpace(StringBuffer str) {
return str.toString().replaceAll(" ","要替换的字符(串)");
}
}
思路二:indexOf("aa",n)从索引n开始,返回第一次出现aa的索引;deleteCharAt(index)删除index位置处的索引;insert(index,"bb")在索引index处插入bb;结合这几个方法,就可以达到替换的目的
public class Solution {
public String replaceSpace(StringBuffer str) {
int n = 0;
while(str.indexOf(" ",n)!= -1){
int index = str.indexOf(" ",n);
str.deleteCharAt(index);
str.insert(index,"%20");
n+=2;
}
return str.toString();
}
}
本文介绍两种在Java中替换字符串空格的方法:一是使用replaceAll()函数直接替换,二是通过indexOf(), deleteCharAt()和insert()组合实现逐个字符的替换。这两种方法各有优劣,可根据具体需求选择使用。
1749

被折叠的 条评论
为什么被折叠?



