替换空格:
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路:先统计一共有多少个空格,然后将指针指向原字符串最后+2n的位置,开始从后往前复制,遇到‘ ’就添加‘%20’。(别忘了最后还有/0)
如”we are",先统计有一个空格,然后新建指向6+21=8的指针t,然后复制
str指针 | t指针 | 剩余空格数 |
---|---|---|
w e “——” a r e /0 | w e“——”a r e - - /0 | 1 |
-------------------↑ | w e“——”a r e - e/0 | 1 |
-----------------↑ | w e“——”a r e r e/0 | 1 |
---------------↑ | w e“——”a r a r e/0 | 1 |
---------↑ | w e“——”a 0 a r e/0 | 1 |
---------↑ | w e“——”2 0 a r e/0 | 1 |
---------↑ | w e % 2 0 a r e/0 | 0 |
剩余空格数为0跳出循环
class Solution {
public:
void replaceSpace(char *str,int length) {
//string a = " a b c";
//char *str = &a[0];
string aa = "%20";
int n = 0;
//int length = a.size();
for (int i = 0; i < length; i++) {
if (*str == ' ') {
n++;
}
str++;
}
char *t = str + (2 * n);
for (int i = 0; i < n;) {
if (*str != ' ') {
*t = *str;
t--;
}
else {
*t-- = '0';
*t-- = '2';
*t-- = '%';
i++;
}
str--;
}
return ;
}
};
网友评论