简体   繁体   English

C - 查找句子中最长的单词

[英]C - Find longest word in a sentence

Hi I have this program that reads a text file line by line and it's supposed to output the longest word in each sentence. 嗨,我有这个程序,逐行读取文本文件,它应该输出每个句子中最长的单词。 Although it works to a degree, it's overwriting the biggest word with an equally big word which is something I am not sure how to fix. 虽然它在某种程度上起作用,但它用一个同样大的词覆盖了最大的单词,这是我不确定如何解决的问题。 What do I need to think about when editing this program? 编辑此程序时需要考虑什么? Thanks 谢谢

//Program Written and Designed by R.Sharpe
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include "memwatch.h"

int main(int argc, char** argv)
{
    FILE* file;
    file = fopen(argv[1], "r");
    char* sentence = (char*)malloc(100*sizeof(char));
    while(fgets(sentence, 100, file) != NULL)
    {
        char* word;
        int maxLength = 0;
        char* maxWord;
        maxWord = (char*)calloc(40, sizeof(char));
        word = (char*)calloc(40, sizeof(char));
        word = strtok(sentence, " ");
        while(word != NULL)
        {
            //printf("%s\n", word);
            if(strlen(word) > maxLength)
            {
                maxLength = strlen(word);
                strcpy(maxWord, word);
            }
            word = strtok(NULL, " ");
        }
        printf("%s\n", maxWord);
        maxLength = 0; //reset for next sentence;
    }

    return 0; 
}

My textfile that the program is accepting contains this 我接受程序的文本文件包含这个

some line with text 
another line of words 
Jimmy John took the a apple and something reallyreallylongword it was nonsense

and my output is this 我的输出就是这个

text

another
reallyreallylongword

but I would like the output to be 但我想输出

some
another
reallyreallylongword

EDIT: If anyone plans on using this code, remember when you fix the newline character issue don't forget about the null terminator. 编辑:如果有人计划使用此代码,请记住修复换行符问题时不要忘记空终止符。 This is fixed by setting sentence[strlen(sentence)-1] = 0 which in effect gets rid of newline character and replaces it with null terminating. 这是通过设置句子[strlen(sentence)-1] = 0来解决的,它实际上取消了换行符并用null终止替换它。

You get each line by using 你通过使用获得每一行

fgets(sentence, 100, file)

The problem is, the new line character is stored inside sentence . 问题是,新行字符存储在sentence For instance, the first line is "some line with text\\n" , which makes the longest word "text\\n" . 例如,第一行是"some line with text\\n" ,这使得最长的单词"text\\n"

To fix it, remove the new line character every time you get sentence . 要解决此问题,请在每次收到sentence时删除新行字符。

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

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