c - 打印字符串中最长的单词

标签 c

我写了下面的代码

#include<stdio.h>

int main(void)
{
    int i, max = 0, count = 0, j;
    char str[] = "I'm a programmer";

    for(i = 0; i < str[i]; i++)
    {
        if (str[i] != ' ')
            count++;
        else
        {
            if (max < count)
            {
                j = i - count;
                max = count;
            }
            count = 0;
        }
    }
    for(i = j; i < j + max; i++)
        printf("%c", str[i]);

    return 0;
}

本意是查找并打印最长的单词,但当最长的单词 this 在最后作为 我是一名程序员 我打印 时不起作用> 而不是程序员

如何解决这个问题,有人帮我

最佳答案

for 循环的终止条件是错误的。应该是:

    for(i = 0; i < strlen(str) + 1; i++)

而且,因为在字符串末尾没有有一个' ',但是有一个'\0' ,你应该改变:

    if (str[i] != ' ')

至:

    if (str[i] != ' ' && str[i] != '\0')

关于c - 打印字符串中最长的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30830330/

相关文章:

c++ - 如何将ANSI C结构转换为C++类,但保持其对ANSI C的友好性?

CC2541 IAR 输出

编译错误 - sysdeps/i386/elf/start.S 和对 main 的 undefined reference

c - 调用 srand() 时遇到读取变量错误(无法访问地址处的内存)

python - 将 C 代码转换为 Web Assembly 时出错

c - 使用 insmod 时 undefined symbol

C实现暴力破解数独不起作用

c++ - 未初始化的值用法,使用sprintf或strcat时出错

C - printf 无符号整型

c++ - 将 _msize 与 new[] 一起使用安全吗?