c - K&R c programming book 3.7 trim函数示例

标签 c

我一直在关注 K&R book 2nd version for c programming,但在 3.7 部分,这里是函数的屏幕截图和我的代码部分:

enter image description here

#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;
}

以下是我运行它得到的输出:

enter image description here

明明结果长度是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/

相关文章:

c - 使用组合管道和重定向编写 C Shell

c - IEEE 754 舍入或斩波

c - 为什么结果是零,而不是正确的 sqrt?

c - 求解使 5x5 对称矩阵奇异所需的值

c - 调用strcat()时如何使用malloc?

在 C 中使用宏连接代码

C 多个 pthread 调用另一个文件中的函数并将值作为全局变量存储到其中

将大写更改为小写,反之亦然,无需使用函数和 if 语句

c - 测量执行某些指令所需时间的最有效和正确的方法是什么?

c - 缓冲区溢出 - linux 64bit