public class replaseImplBySelf {
public static void main(String[] args) {
String a = " a n f g";
System.out.println(StringReplase(a));
}
/**
* @param str
* str == null 直接返回
* str没有空格直接返回
* @return
*/
private static String StringReplase(String str) {
if (str == null) {
return str;
}
int count = 0;
char[] strCharArray = str.toCharArray();
for(char singleStr:strCharArray){
if(singleStr == ' '){
count++;
}
}
if(count == 0){
return str;
}
char[] newCharArray = new char[str.length()+count*2];
int sum = newCharArray.length-1;
//int index = --sum;
for(int i=strCharArray.length-1;i>=0;i--){
if(strCharArray[i]!= ' '){
newCharArray[sum--] = strCharArray[i];
}else{
newCharArray[sum--] = '0';
newCharArray[sum--] = '2';
newCharArray[sum--] = '%';
}
}
StringBuffer sb = new StringBuffer();
for(int j = 0;j<newCharArray.length;j++){
sb.append(newCharArray[j]);
}
System.out.println("back:"+sb.toString());
return sb.toString();
}
}
肯定不能直接用replase()或replaseAll(),相当于手动实现一遍replase源码
思路:
把原数组的空格全都变为"%20",然后放到新数组里面,
新建长度为原数组长度+空格数量*2的新数组,因为
原数组长度已经包含一个空格的长度了,所以乘2就可以了
之后就是判断如果原数组当前值不为空,就放到新数组,
为空就把%20依次放到新数组,注意我写的是从后往前遍历
,和从前向后遍历是一样的
that it