题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
public class Solution {
public String replaceSpace(StringBuffer str) {
if(str==null) return null;
int oldLen=str.length();
int count=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)==' '){
count++;
}
}
int newLen=str.length()+count*2;
str.setLength(newLen);
int before=oldLen-1;
int after=newLen-1;
while(before >= 0 && before < after){
char temp=str.charAt(before);
if(temp==' '){
str.setCharAt(after,'0');
str.setCharAt(after-1,'2');
str.setCharAt(after-2,'%');
after-=3;
}else{
str.setCharAt(after,temp);
after--;
}
before--;
}
return str.toString();
}
}
在牛客网上看到别人的思路也不错:
public class Solution {
public String replaceSpace(StringBuffer str) {
String sti = str.toString();
char[] strChar = sti.toCharArray();
StringBuffer stb = new StringBuffer();
for(int i=0;i<strChar.length;i++){
if(strChar[i]==' '){
stb.append("%20");
}else{
stb.append(strChar[i]);
}
}
return stb.toString();
}
}