我遇到过这个面试问题,并希望在尝试理解其解决方案时提供一些帮助:
编写一个方法来用'%20'替换字符串中的所有空格.
解决方案(来自论坛):
char str[]="helo b";
int length = strlen(str);
int spaceCount = 0, newLength, i = 0;
for (i = 0; i < length; i++) {
if (str[i] == ' ') {
spaceCount++; //count spaces...
}
}
newLength = length + spaceCount * 2; //need space for 2 more characters..
str[newLength] = '\0';
for (i = length - 1; i >= 0; i--) {
if(str[i] == ' ') {
str[newLength - 1] = '0'; //???
str[newLength - 2] = '2';
str[newLength - 3] = '%';
newLength = newLength - 3;
} else {
str[newLength - 1] = str[i];
newLength = newLength - 1;
}
}
Run Code Online (Sandbox Code Playgroud)
这个程序对我不起作用...我首先想在深入研究代码之前先了解算法.
Eri*_*rik 12
那个样本坏了.
缓冲区溢出,字符串的一个无意义扫描(strlen),难以阅读.
int main() {
char src[] = "helo b";
int len = 0, spaces = 0;
/* Scan through src counting spaces and length at the same time */
while (src[len]) {
if (src[len] == ' ')
++spaces;
++len;
}
/* Figure out how much space the new string needs (including 0-term) and allocate it */
int newLen = len + spaces*2 + 1;
char * dst = malloc(newLen);
/* Scan through src and either copy chars or insert %20 in dst */
int srcIndex=0,dstIndex=0;
while (src[srcIndex]) {
if (src[srcIndex] == ' ') {
dst[dstIndex++]='%';
dst[dstIndex++]='2';
dst[dstIndex++]='0';
++srcIndex;
} else {
dst[dstIndex++] = src[srcIndex++];
}
}
dst[dstIndex] = '\0';
/* Print the result */
printf("New string: '%s'\n", dst);
/* And clean up */
free(dst);
return 0;
}
Run Code Online (Sandbox Code Playgroud)