劍指offer——(2)替換空格
阿新 • • 發佈:2018-11-12
public class Solution {
public String replaceSpace(StringBuffer str) {
/*
思路一:return str.toString().replace(" ", "%20");
思路二:計算字串的空格數量,空出對應的位置依次插入'%''2''0'三個字元
*/
char c[] = new char[str.length()];
int count = 0;
for(int i=0;i<c.length;i++) {
c[i] = str.charAt(i);
if(c[i]==' ') {
count++;
}
}
char chr[] = new char[c.length+count*2];
for(int i = 0,j = 0;i<c.length&&j<chr.length;) {
if(c[i]==' ') {
chr[j++] = '%';
chr[j++] = '2';
chr[j++] = '0';
}
else {
chr[j] = c[i];
j++;
}
i++;
}
/*
toString方法出現亂碼?!
return chr.toString(); // [ [email protected]
*/
return String.valueOf(chr);
}
}