替换空格

题目描述

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

解题思路

先从前到后遍历一次,计算有多少个空格,然后再从后到前逐个替换。

代码实现

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
void replaceSpace(char *str,int length) {
int count=0;
for(int i=0;i<length;i++){
if(*(str+i)==' ')
count++;
cout << *(str+i);
}

for (int i = length - 1; i >= 0; i--){
if (*(str+i) != ' '){
*(str+i+count*2) = *(str+i);
}else{
count--;
*(str+i+(count)*2) = '%';
*(str+i+(count)*2+1) = '2';
*(str+i+(count)*2+2) = '0';
}
}
}
};

Java

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
public class Solution {
public String replaceSpace(StringBuffer str) {
char ch[] = str.toString().toCharArray();
int count = 0;
for (int i = 0; i < ch.length; i++) {
if (ch[i] == ' ') {
count++;
}
}

char tmp[] = new char[ch.length + 2 * count];

for (int i = ch.length-1; i >= 0; i--) {
if (ch[i] != ' ') {
tmp[i + 2 * count] = ch[i];
} else {
tmp[i + 2 * count] = '0';
tmp[i + 2 * count - 1] = '2';
tmp[i + 2 * count - 2] = '%';
count--;
}
}
return String.valueOf(tmp);
}
}