替换空格

题目描述

请实现一个函数,将一个字符串中的每个空格替换成 “%20”。例如,当字符串为 We Are Happy. 则经过替换之后的字符串为 We%20Are%20Happy。

替换空格

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public String replaceSpace(StringBuffer str) {
if (str == null || str.length() == 0){
return "";
}
// 1. 得到原来字符串的长度
int originLength = str.length();
// 2. 计算空白格的个数
int blankNumber = 0;

for (int i = 0; i < originLength; i++){
if (str.charAt(i) == ' '){
++blankNumber;
}
}
//3. 拿到新的字符串长度
int newLength = originLength + blankNumber * 2;

//4. 用两个指针分别指向 原来字符串的最后一个字符 和 新的字符串的最后一个字符
int originIndex = originLength - 1;
int newIndex = newLength - 1;
// 5. 更新 StringBuffer 的长度
str.setLength(newLength);

while (originIndex >= 0 && newIndex > originIndex){
if (str.charAt(originIndex) == ' '){ // 如果字符为空,那么替换为 %20,newIndex 逐步向前移动
str.setCharAt(newIndex--, '0');
str.setCharAt(newIndex--,'2');
str.setCharAt(newIndex--,'%');
} else { //如果字符不为空,那么将原有字符串的字符 复制 到 新的字符串的位置上
str.setCharAt(newIndex--, str.charAt(originIndex));
}
--originIndex; //操作一次,原有指针都要往前移动
}
return str.toString();
}