一、问题描述:将一个字符串中的空格替换成 “%20”。
二、解题思路:
1.直接使用String的replace(" “,”%20"),感觉直接调API没锻炼到解题能力
public String replaceSpace(StringBuffer str) {
return str.toString().replace(" ","%20");
}
2.不调用API的解法:先遍历字符串,发现空格就在字符串后面添加两个空格,这样遍历完就可以得到替换后的字符串长度。然后从旧字符串长度和新字符串长度往前遍历,如果是空格就将新字符串的后三个字符设置为"%20",如果不是空格就将当前字符赋值到新字符串的最后一位,以此类推
public String replaceSpace(StringBuffer str) {
int len = str.length() - 1;
for(int i = 0; i <= len; i++) {
if(str.charAt(i) == ' ') {
str.append(" ");
}
}
for(int i = len,j = str.length() - 1; i >= 0 && j > i; i--) {
if(str.charAt(i) == ' ') {
str.setCharAt(j--, '0');
str.setCharAt(j--, '2');
str.setCharAt(j--, '%');
}else {
str.setCharAt(j--, str.charAt(i));
}
}
return str.toString();
}
3.假设让你实现replace(old,new)方法,你会怎么做?思考一下(这里的replace方法不是替换字符,是替换字符串,replace有多个重载方法)
我的想法:对原字符串进行遍历,如果没找到需要替换的子串,则使用System.arrayCopy(oldString,0,newString,i,count)将已经遍历过的字符串子串复制到新字符串中去,如果找到要替换的子串时(此处的count表示已经遍历过的字符串子串长度),使用System.arrayCopy(new,0,newString,i,count)将替换的子串复制到新字符串去(此处的count是new字符串的长度),i是动态变化的,一开始为0,每次需要进行i += count运算