【问题标题】:C - Find longest word in a sentenceC - 查找句子中最长的单词
【发布时间】:2014-09-26 11:12:22
【问题描述】:

您好,我有这个程序可以逐行读取文本文件,它应该输出每个句子中最长的单词。尽管它在一定程度上起作用,但它会用同样大的单词覆盖最大的单词,这是我不知道如何解决的问题。编辑这个程序时我需要考虑什么?谢谢

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

程序接受的我的文本文件包含这个

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

我的输出是这样的

text

another
reallyreallylongword

但我希望输出是

some
another
reallyreallylongword

编辑:如果有人计划使用此代码,请记住在修复换行符问题时不要忘记空终止符。这是通过设置修复的 sentence[strlen(sentence)-1] = 0 实际上去掉了换行符并将其替换为空终止符。

【问题讨论】:

  • word = (char*)calloc(40, sizeof(char)); 是内存泄漏,因为在下一行你说word = ...
  • 好吧,我通过使用 calloc 为 word 分配空间,然后我为 char* 指针分配一个值,对吗?怎么会是内存泄漏?
  • 不。您分配了一些内存(word 是您指向它的指针)。然后你说word = ...,所以你有很多指向分配内存的指针。如果您不相信我,只需将calloc 注释掉,它仍然可以完全一样的工作;-)
  • calloc() word 将指向新创建的内存之后,然后在下一行它指向strok 返回的不同内存地址,因此分配的内存丢失了,而且你没有在任何地方删除它
  • 假设第一行是Some line with text.——你希望text.把句点算作长度为5的单词吗?如果没有,您需要在strtok() 调用中添加更多分隔符——换行符、制表符、各种标点符号。单引号会使事情变得棘手; doesn't 是一两个字吗? He said, 'That is a line!' 呢?单引号并不是单词的真正组成部分。你可以在这里做出各种合理的决定,只要你是自洽的,这对你正在进行的练习可能并不重要(但“自洽”是一两个词吗?)。

标签: c text input


【解决方案1】:

你得到每一行使用

fgets(sentence, 100, file)

问题是,换行符存储在sentence 中。例如,第一行是"some line with text\n",这是最长的单词"text\n"

要解决此问题,请在每次收到 sentence 时删除换行符。

【讨论】:

  • 或者让分隔符列表包括换行符(也可能是制表符,也可能是其他字符)。
  • 我删除了 '\n' 字符,后来杀死我的是我认为我也删除了空终止符,这导致看起来正确的代码出现了很多问题。用空终止符替换换行符被替换为 sentence[(strlen(sentence)-1] = 0
  • @OP sentence[(strlen(sentence)-1] = 0strlen(sentence)'\0' 的极少数情况下也有问题,例如'\0' 存在于'\n' 之后的文件中。建议@Jonathan Leffler 对此解决方案进行修改。
猜你喜欢
  • 2023-04-08
  • 1970-01-01
  • 2023-03-14
  • 1970-01-01
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多