剑指offer(2):替换空格
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution { public: void replaceSpace(char *str,int length) { int newlength = 0, blank_number = 0, str_len = 0, tail = 0; for(str_len = 0; str[str_len] != '\0'; str_len++) { if(str[str_len] == ' ') blank_number += 2; } newlength = str_len + blank_number; if(newlength > length) return; str[newlength] = '\0'; tail = newlength - 1; for( auto i = str_len - 1; i >= 0; i--) { if( str[i] == ' ') { str[tail--] = '0'; str[tail--] = '2'; str[tail--] = '%'; } else str[tail--] = str[i]; } } };