题目:实现一个函数,把字符串中每个空格都替换成%20,例如输入“we are happy!!!”,输出“we%20are%20happy!!!” 思路: 1、若内存够多,可另开辟一足够大字符串,在新字符串上做替换,实现思路简单。 2、在原来字符串上修改,并保证后面有足够空间。 代码: void ReplaceBlank(char* str,int strsize) { if (str == NULL || strsize <= 0) { return; } int countBlank = 0; int countStr = 0; char* p = str; while (*(p) != '\0') { countStr++; if (*p == ' ') { countBlank++; } p++; } int newLength = countStr + 2 * countBlank; if (newLength > strsize) //存不下 { return; } while (countStr >= 0 && newLength > countStr) { if (str[countStr] != ' ') { str[newLength--] = str[countStr--]; } else //遇到空格 { str[newLength--] = '0'; str[newLength--] = '2'; str[newLength--] = '%'; countStr--; } } } int main() { char str[50] = "we are happy!!!"; int sz = strlen(str); ReplaceBlank(str,50); cout << str << endl; system("pause"); }