剑指offer-替换空格
替换空格
https://www.nowcoder.com/practice/4060ac7e3e404ad1a894ef3e17650423?tpId=13&tqId=11155&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
题目
实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
思路
在原字符串上添加,首先计算出空格的数量,同时根据此计算出字符串扩充后的长度,从后向前添加。
代码
class Solution { public: void replaceSpace(char *str,int length) { int numofblack = 0;/*空格数量*/ int index2 = 0;/*延长后的字符串的索引*/ int length1 = 0 ;/*字符串长度*/ //int i = 0 ;/* 遍历字符串的索引 */ if (length <= 0) { return; } //while (str[i] != "/0") for (int i = 0; i < length; i++) { if (str[i] == ' ') { numofblack++; } } index2 = length + 2*numofblack - 1; for (int j = length - 1; j >= 0; j--) { if (str[j] == ' ') { str[index2] = '0'; str[--index2] = '2'; str[--index2] = '%'; index2--; } else { str[index2] = std::move (str[j]); index2--; } } } };