请实现一个函数,将一个字符串中的每个空格替换成
“%20”
。例如,当字符串为We Are Happy.
则经过替换之后的字符串为We%20Are%20Happy
class Solution {
public:
void replaceSpace(char *str,int length) {
}
};
只借助
指向的字符串,从后向前依次移动;
一个空格最后替换成'%''2''0'
,一个字符替换为三个字符,相当于增加了2个字符;
一个循环统计字符串中空格的个数,替换之后的字符串长度就是原来字符串长度加上空格数的2倍.
两个变量
分别记录原来字符串的最后一个字符的下标与新字符串的最后一个字符的下标;
一个循环,如果下标
的字符不是空格,就把
下标的字符移动到
下标位置,之后两个下标均减1;
如果下标
的字符是空格,
减1,,把'0'、'2'、'%'
这三个字符依次存入下标
位置,每次存入后都
;
当空格替换完成时,end1与end2相等,结束循环。
class Solution {
public:
void replaceSpace(char *str,int length) {
//找空格数
int cnt = 0;
char* start = str;
while(*start){
if(*start == ' '){
cnt++;
}
start++;
}
//从后向前移,遇到空格
//前后下标
int end1 = length - 1;
int end2 = length - 1 + 2*cnt;
while(end1 != end2){
if(str[end1] != ' '){
str[end2--] = str[end1--];
}
else{
str[end2--] = '0';
str[end2--] = '2';
str[end2--] = '%';
end1--;
}
}
}
};
class Solution {
public:
void replaceSpace(char *str,int length) {
//找空格数量
char* start = str;
int cnt = 0;
while (*start) {
if (*start == ' ') {
cnt++;
}
start++;
}
int len1 = length;
int len2 = length + 2 * cnt;
//创建数组存放新字符串
char* s = (char*)malloc(sizeof(char) * (len2+1));
start = str;
char* ps = s;
while (*start) {
if (*start != ' ') {
*ps++ = *start++;
}
else {
start++;
*ps++ = '%';
*ps++ = '2';
*ps++ = '0';
}
}
*ps = '\0';
strcpy(str, s);
free(s);
s = NULL;
}
};
本体有两种思路:
第一种方法是从后往前放,不需要创建新数组。
第二种是常规方法,从前往后放。新创建一个字符数组,把原来字符串的内容依次放入创建的字符数组,遇到空格字符就放入三个字符‘%’、‘2’、‘0’
到字符数组中,直到遇到字符串末尾。再把字符数组的内容复制回原来的字符串中。