剑指Offer_编程题_2
题目描述
请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
class Solution { public: void replaceSpace(char *str,int length) { int oldStringLength; int numBlank = 0; for(oldStringLength = 0; str[oldStringLength]!='\0';oldStringLength++) { if (str[oldStringLength] == ' ') { numBlank++; } } int curStringLength = oldStringLength + numBlank * 2; if (curStringLength > length) return; str[curStringLength] = '\0'; for(int j = oldStringLength-1,i = curStringLength-1; j != i; j--) { if (str[j] == ' ') { str[i] = '0'; str[i-1] = '2'; str[i-2] = '%'; i = i-3; } else { str[i] = str[j]; i--; } } } };