我一直在关注 K&R book 2nd version for c programming,但在 3.7 部分,这里是函数的屏幕截图和我的代码部分:
#include <stdio.h>
#include <string.h>
/* trim: removing the trailing blanks, tabs and newlines */
int trim(char s[]);
int main(){
char s[] = "hello,world \t\t\t\t\n\n\n\n";
printf("%s\n", s);
int length = trim(s);
printf("%d\n", length);
return 0;
}
int trim(char s[]){
int n;
for (n = strlen(s) -1 ; n >= 0 ; n--)
if (s[n] != ' ' && s[n] != '\n' && s[n] != '\t')
break;
s[n+1] = '\0';
return n;
}
以下是我运行它得到的输出:
明明结果长度是11,"hello,world",但是程序输出了10, 原因是s[n+1] = '\n',而不是s[++n];我觉得应该是s[++n], 否则我会得到错误的输出 ==> 10,如何处理?有人可以看看吗?
最佳答案
我会遍历 length 并向前(向后?)看一个元素,看看我们是否需要修剪它:
int trim(char s[]) {
int n;
for(n = strlen(s); n > 0; n--)
if(s[n-1] != ' ' && s[n-1] != '\t' && s[n-1] != '\n')
break;
s[n] = '\0';
return n;
}
关于c - K&R c programming book 3.7 trim函数示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66650156/