题目:
请实现一个函数,把字符串中的每个空格替换成"%20"。例如输入“We are happy.”,则输出“We%20are%20happy.”。
实现:
//方法一: 若可创建新的字符串,若果字符串上第i为为空格,则添加%20,否则添加这个位置上的字符
//StringBuffe 也有charAt() 和lenth()
public class Solution {
public String replaceSpace(StringBuffer str) {
StringBuffer res =new StringBuffer();
int n=str.length();
for(int i=0;i<n;i++){
if(str.charAt(i)==' ')
res.append("%20");
else
res.append(str.charAt(i));
}
return res.toString();
}
}
//方法二:若果不能创建新的字符串,只能在原字符串上替换,就先算出字符串的总长度,从后边开始一次向前
public class Solution {
public String replaceSpace(StringBuffer str) {
int len1=str.length();
int count=0;
for(int i=0;i<len1;i++){
if(str.charAt(i)==' ')
count++; //算出空格的个数
}
int len2=len1+count*2;//算出新字符串的总长度
int j=len1-1;
int i=len2-1;
str.setLength(len2); //设置其总长度
while(j>=0&&i>=0){ //从新串和旧串的后边开始依次向前
if(str.charAt(j)==' '){
str.setCharAt(i--, '0');
str.setCharAt(i--, '2');
str.setCharAt(i--, '%');
}else
str.setCharAt(i--,str.charAt(j));
j--;
}
return str.toString();
}
}