题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路1:
每多一个空格,则新的字符串会多出两个空间,所以申请一个新的字符串如下:
char
*array =
new
char
[length +
2
*space]
遍历原字符串,按照修改规则向新字符串中逐个添加字符。而后将新字符的内容拷贝给原字符串
class Solution { public: void replaceSpace(char *str,int length) { int space = 0; for(int i=0;i<length;i++) { if(*(str+i) == ' ') { space++; } } char *array = new char[length + 2*space]; int new_pos = 0; for(int i=0;i<length;i++) { if(*(str+i)!= ' ') { *(array+new_pos++) = *(str+i); } else { *(array+new_pos++) = '%'; *(array+new_pos++) = '2'; *(array+new_pos++) = '0'; } } strcpy(str,array); } };
思路2:
在不开辟新的字符串的情况下,直接在原字符串上做更改。
为了保证“无后效性”,逆序扫描原字符串,并将当前扫描的字符,填充在新位置。
class Solution { public: void replaceSpace(char *str,int length) { if(str == nullptr || length<=0) return; int space = 0; for(int i=0;i<length;i++) { if (*(str+i)==' ') space++; } if(!space) return; int old_pos = length; int new_pos = length+2*space; for(int i=old_pos;i>=0;i--) { if(*(str+i) != ' ') { *(str+new_pos--) = *(str+i); } else { *(str+new_pos--) = '0'; *(str+new_pos--) = '2'; *(str+new_pos--) = '%'; } } } };
注意事项:
应注意细节上的实现,比如:
在执行后续操作前,通过 if(str == nullptr || length<=0) 检查传入的是否为空指针
若原字符串中没有空格,则不需要进行后续操作