方法一
String str="we are happy";
String str1=str.replaceAll(" ", "20%");
System.out.println(str1);
we20%are20%happy
使用replaceAll
是最简单的,但是我这道题要求不能使用replaceall,同时,不能新增字符串对象
方法二
public String myAtoi(StringBuffer str) {
int length = str.length();
int spacenum = 0;
//统计空格字符个数
for(int i=0;i<length;i++){
if(str.charAt(i) == ' ')
spacenum++;
}
int lengthNew = length + spacenum*2;
str.setLength(lengthNew);
int index = length-1;
int indexNew = lengthNew-1;
for(;index>=0;index--){
if(str.charAt(index) == ' '){
str.setCharAt(indexNew--, '0');
str.setCharAt(indexNew--, '2');
str.setCharAt(indexNew--, '%');
}
else{
str.setCharAt(indexNew--, str.charAt(index));
}
}
return str.toString();
}