question:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
解法一:使用replace方法
思路: 感觉有些取巧了
public class Solution {
public String replaceSpace(StringBuffer str) {
String s = str.toString();
return s.replaceAll(" ","%20");
}
}
解法二:不使用replace方法一
思路: 新创建一个新字符串,遍历原字符串如果遇到空格那么改为“%20”,感觉费点时间。
public class Solution {
public String replaceSpace(StringBuffer str) {
int len = str.length();
StringBuffer sb = new StringBuffer();
for(int i=0;i<len;i++){
if(str.charAt(i)==' '){
sb.append("%20");
}else{
sb.append(str.charAt(i));
}
}
return sb.toString();
}
}
解法三:不用replace的方法二
思路:不创建新的字符串,直接在原字符串上操作。主要是他用了 str.setLength(newlength);
学习一波。别的倒是无所谓。
public class Solution {
public String replaceSpace(StringBuffer str) {
int spacenum = 0;//spacenum为计算空格数
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' ')
spacenum++;
}
int indexold = str.length()-1; //indexold为为替换前的str下标
int newlength = str.length() + spacenum*2;//计算空格转换成%20之后的str长度
int indexnew = newlength-1;//indexold为为把空格替换为%20后的str下标
str.setLength(newlength);//使str的长度扩大到转换成%20之后的长度,防止下标越界
for(;indexold>=0 && indexold<newlength;--indexold){
if(str.charAt(indexold) == ' '){ //
str.setCharAt(indexnew--, '0');
str.setCharAt(indexnew--, '2');
str.setCharAt(indexnew--, '%');
}else{
str.setCharAt(indexnew--, str.charAt(indexold));
}
}
return str.toString();
}
}