问题描述: 请实现一个函数,将一个字符串中的空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
最初实现(添加了一些检测):
1 class Solution { 2 public: 3 void replaceSpace(char *str,int length) 4 { 5 if(str == NULL || length < 0) 6 return; 7 int oldLen = 0; // 旧字符个数 8 int spaceSum = 0; // 记录空格数量 9 for(int i = 0; str[i] != ‘\0‘; i++) 10 { 11 if (str[i] == ‘ ‘) 12 spaceSum++; 13 oldLen++; 14 } 15 16 int newLen = 2 * spaceSum + oldLen; 17 if(newLen > length) 18 return; 19 int j = oldLen; 20 int k = newLen; 21 while( j >= 0 && k > j) 22 { 23 if(str[j] == ‘ ‘) 24 { 25 j--; 26 str[k--] = ‘0‘; 27 str[k--] = ‘2‘; 28 str[k--] = ‘%‘; 29 } 30 else 31 { 32 str[k--] = str[j--]; 33 } 34 } 35 } 36 };
据说指针更快一些,那就修改成指针再刷一下题:
1 void replaceSpace(char *str,int length) 2 { 3 if(str == NULL || length < 0) 4 return; 5 int oldLen = 0; // 旧字符个数 6 int spaceSum = 0; // 记录空格数量 7 for(int i = 0; str[i] != ‘\0‘; i++) 8 { 9 oldLen++; 10 if (str[i] == ‘ ‘) 11 ++spaceSum; 12 } 13 14 int newLen = 2 * spaceSum + oldLen; 15 if(newLen > length) 16 return; 17 char* OldStr = str + oldLen; 18 char* NewStr = str + newLen; 19 while( NewStr > OldStr) 20 { 21 if(*OldStr == ‘ ‘) 22 { 23 *NewStr-- = ‘0‘; 24 *NewStr-- = ‘2‘; 25 *NewStr-- = ‘%‘; 26 } 27 else 28 { 29 *NewStr-- = *OldStr; 30 } 31 --OldStr; 32 } 33 }