public String replaceSpace(StringBuffer str) {
int n = str.length(); // str 的 初始长度
//遍历该字符串,遇到空格就添加 2 个空格
//因为要将 " " -> "%20",1 个字符替换成 3 个字符,则需要额外的两个字符
for(int i=0;i<n;i++){
if(str.charAt(i)==' '){
str.append(" ").append(" ");
}
}
int p1 = n-1;//p1 指向字符串最后一位
int p2 = str.length()-1;//p2 指向新字符串最后一位
//从后向前遍是为了在改变 p2 所指向的内容时,不会影响到 p1 遍历原来字符串的内容。
while(p1>=0 && p2>p1){ // p1==p2 则前面的元素就不需要遍历了,是存在空格的
char ch = str.charAt(p1--);
if(ch==' '){ //" " -> "%20" ,由于是从后向前的,所以要倒序填充
str.setCharAt(p2--,'0');
str.setCharAt(p2--,'2');
str.setCharAt(p2--,'%');
}else{
str.setCharAt(p2--,ch);
}
}
return str.toString();
}
https://www.mianshi.online,[https://www.i9code.cn](
本文由博客一文多发平台 OpenWrite 发布!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。