您的位置:首页 > Web前端

剑指offer之替换空格

2017-03-07 22:35 537 查看
 思路1:将字符串先转化为字符数组,声明一个StringBuffer变量,如果字符为非空格,则追加该字符,否则追加%20

public String replaceSpace(StringBuffer str) {
if (str == null)
return null;

char[] array = str.toString().toCharArray();
StringBuffer s = new StringBuffer();
for (int i = 0; i < array.length; i++) {
if (array[i] == ' ') {
s.append("%20");
continue;
}
s.append(array[i]);
}
return s.toString();
}

思路2:从后往前替换
public String replaceSpace(StringBuffer str) {

if (str == null)
return null;
int spaceNum = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
spaceNum++;
continue;
}
}
int oldLength = str.length();
int newLength = oldLength + spaceNum * 2;
str.setLength(newLength);
for (int oldIndex = oldLength - 1, newIndex = newLength - 1; oldIndex >= 0
&& oldIndex < newIndex; --oldIndex) {
if (str.charAt(oldIndex) == ' ') {
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--, '2');
str.setCharAt(newIndex--, '%');
} else {
str.setCharAt(newIndex--, str.charAt(oldIndex));
}
}
return str.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: