简体   繁体   English

打印字符串中最长的单词

[英]Print the longest word of a string

I wrote the following code 我写了以下代码

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

With the intention to find and print the longest word, but does not work when the longest word this in the last as I'm a programmer I printed I'm instead of programmer 打算找到并打印最长的单词,但是当最后一个字最后一个因为我是程序员而打印时, 打印的不是程序员

How to solve this problem, someone gives me a hand 如何解决这个问题,有人帮我一把

The terminating condition of your for loop is wrong. 你的for循环的终止条件是错误的。 It should be: 它应该是:

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

and also, since at the end of string you don't have a ' ' , but you have a '\\0' , you should change: 而且,因为在字符串的末尾你没有 ' ' ,但你有一个'\\0' ,你应该改变:

    if (str[i] != ' ')

to: 至:

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

The issue should be rather obvious. 问题应该是显而易见的。 You only update your longest found word when the character you are inspecting is a space. 当您正在检查的角色是空格时,您只更新找到的最长的单词。 But there is no space after the longest word in your test string, thus updating code is never exeuted for it. 但是在测试字符串中最长的单词之后没有空格,因此更新代码永远不会被执行。

You can just plop this code after the loop and that should do the trick. 您可以在循环之后填充此代码,这应该可以解决问题。

Note however you could have trivially found this by adding mere printfs showing progress of this function. 但请注意,通过添加显示此功能进度的printfs,您可以轻而易举地找到它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM