gpt4 book ai didi

C 查找字典中的所有字谜

转载 作者:太空宇宙 更新时间:2023-11-04 08:19:42 24 4
gpt4 key购买 nike

我正在尝试编写一个程序来查找字典(Linux 中的/usr/share/dict/words 文件)中的所有变位词(通过重新排列字母重新组合的单词)。字典文件包含很多以“'s”结尾的单词,我想将其从检查中排除。这是我为此写的,但不幸的是,结果文件包含只有一个字母“s”的行,我不知道它来自哪里。

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define TRUE 1
#define FALSE 0

int wordContainsNonAlpha(char *word);

int main(int argc, const char *argv[]){
FILE *fp_read = fopen("/usr/share/dict/words", "r");
char *word = malloc(sizeof(word));
FILE *fp_write = fopen("words.txt","w");

while (fgets(word,sizeof(word), fp_read) != NULL){
if (wordContainsNonAlpha(word)){
fprintf(fp_write,"%s","\n");
}
else{
// fputs(word, stdout);
fprintf(fp_write,"%s",word);
}
}

fclose(fp_read);
fclose(fp_write);

return 0;
}

int wordContainsNonAlpha(char *word){
int currentLetter = 0;
int wordLenght = strlen(word);
int result = FALSE;
char ch;

while ( (currentLetter < wordLenght) && (result == FALSE) ){
ch = word[currentLetter];
if (ch == '\''){
// if (!isalpha(ch)){
result = TRUE;
break;
}
currentLetter++;
}

return result;
}

结果是:

    $ sdiff words.txt /usr/share/dict/words | more
A A
| A's
| AA's
| AB's
| ABM's
| AC's
| ACTH's
| AI's
| AIDS's
| AM's
AOL AOL
| AOL's
| ASCII's
| ASL's
| ATM's
| ATP's
| AWOL's
| AZ's
| AZT's
<
Aachen Aachen
Aaliyah Aaliyah
Aaliyah | Aaliyah's
Aaron Aaron
Abbas Abbas
Abbasid Abbasid
Abbott Abbott
| Abbott's
s <
Abby Abby
| Abby's
Abdul Abdul
| Abdul's
<
Abe Abe
| Abe's
Abel Abel
........

如果我尝试使用 isalpha 函数,结果会更糟,因为它似乎在寻找具有特定长度的单词并且根本无法正常工作:

sdiff words.txt /usr/share/dict/words | more
| A
| A's
| AA's
| AB's
| ABM's
| AC's
| ACTH's
| AI's
| AIDS's
| AM's
| AOL
| AOL's
| ASCII's
| ASL's
| ATM's
| ATP's
| AWOL's
| AZ's
| AZT's
| Aachen
<
Aaliyah Aaliyah
Aaliyah | Aaliyah's
| Aaron
| Abbas
Abbasid Abbasid
| Abbott
| Abbott's
| Abby
| Abby's
| Abdul
| Abdul's
| Abe
| Abe's
| Abel
| Abel's
<
<
Abelard Abelard
Abelson Abelson
Abelson | Abelson's
Aberdee | Aberdeen
Aberdee | Aberdeen's
Abernat | Abernathy
Abernat | Abernathy's
Abidjan <
Abidjan Abidjan

你能帮忙吗?

最佳答案

您的问题来自您对 malloc() 的调用:

char *word = malloc(sizeof(word));
// Here, you allocate sizeof(char*) bytes which is only the size of a pointer and not the size of a dictionary word


while (fgets(word,sizeof(word), fp_read) != NULL){
// In this case, fgets does not stop when you expect it

要解决这个问题,您可以简单地为您的分配使用一个常量,它是字典中最长单词的长度或任意值(我用 64 快速测试)

关于 isalpha() 的问题,这是因为 fgets() 在您的单词中存储了 '\n'。

来自 man fgets:

If a newline is read, it is stored into the buffer

因此,您可以使用:

    if (ch != '\n' && !isalpha(ch)){

关于C 查找字典中的所有字谜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33955706/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com