2.替换空格——剑指offer
题目描述
请实现一个函数,将一个字符串中的每个空格替换成“%20”。例如,当字符串为We Are Happy.则经过替换之后的字符串为We%20Are%20Happy。
1 //新建一个string,得到结果后strcpy到原str 2 class Solution { 3 public: 4 void replaceSpace(char *str,int length) { 5 string temp; 6 for(int i = 0; *(str + i) !='\0'; ++i){ 7 if(*(str + i) ==' ') temp += "%20"; 8 else temp += *(str + i); 9 } 10 // str = new char[temp.size() + 1]; 11 strcpy(str , temp.c_str()); 12 } 13 };
//从左往右遍历,计算空格数,oldlength+2*num得到新长度 //从右往左遍历得到替换后的字符串 class Solution { public: void replaceSpace(char *str,int length) { int num = 0; int nlength = length; int nindex = 0; for(int i = 0;i < length;i++){ if(str[i]==' ') num++; } nlength += 2*num; nindex = nlength; for(int i = length;i >= 0;i--){ if(i == nindex) break; if(str[i]!=' ') str[nindex--] = str[i]; else{ str[nindex--] = '0'; str[nindex--] = '2'; str[nindex--] = '%'; } } } };