[英]C - Find longest word in a sentence
嗨,我有这个程序,逐行读取文本文件,它应该输出每个句子中最长的单词。 虽然它在某种程度上起作用,但它用一个同样大的词覆盖了最大的单词,这是我不确定如何解决的问题。 编辑此程序时需要考虑什么? 谢谢
//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
编辑:如果有人计划使用此代码,请记住修复换行符问题时不要忘记空终止符。 这是通过设置句子[strlen(sentence)-1] = 0来解决的,它实际上取消了换行符并用null终止替换它。
你通过使用获得每一行
fgets(sentence, 100, file)
问题是,新行字符存储在sentence
。 例如,第一行是"some line with text\\n"
,这使得最长的单词"text\\n"
。
要解决此问题,请在每次收到sentence
时删除新行字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.