c - 使用 4-7 个字母在文本文件中查找整个单词

标签 c windows string text-files codeblocks

我是 C 语言的新手,我很高兴获得有关此程序的任何帮助:

任务:

用户将输入 4-7 个字母(例如“ADFG”)。

我有分离的文本文件,其中包含大约几千个单词

(例如:

  • BDF
  • BGFK
  • JKLI
  • NGJKL
  • POIUE

等)

-它写在没有该标记的列表中

我想制作一个程序,从这个文本文件中查找单词,这些单词与用户输入的字母相同(在这种情况下,当我输入 ADFG 时,它将查找并显示 BDF、BGFK、NGJKL)。

这是我到目前为止的代码:

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

int main() 
{
    char enter[8],row[80];

    printf("4-7 different letteres: ");
    gets(enter);

    if (strlen(enter)>7 || strlen(enter)<4)
    {
        puts("incorrect number of letters"); 
        return 1;
    }

    typedef struct structure
    {
        char row[50];
    }Row;

    Row textrow[40000];

    FILE *file;
    file = fopen("words.txt","r");

    if (file==NULL)
    {
        printf("Error! File %s can not be opened.","words.txt");
        return 1;
    }

    int i=0;
    char words[30];

    while (!feof(file))
    {
        fscanf(file,"%s",&textrow[i].row[0]);
        for(int j=0;j<strlen(enter);j++)
        {
            for(int k=0;k<strlen(textrow[i].row);k++)
            {
                words=strchr(textrow[i].row[k],enter[j]);
                printf("%s",words);
            }
        }
        i++;
    }

    fclose(file);
    return 0;
} 

感谢您的帮助。

最佳答案

例如使用strpbrk

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

int main(){
    char *words[] = {
        "BDF", "BGFK", "JKLI", "NGJKL", "POIUE", NULL
    };
    char enter[8] = "ADFG";
    char **p;
    for(p = words; *p ; ++p){
        char *word = *p;
        if(strpbrk(word, enter)!=NULL){
            printf("%s\n", word);
        }
    }
/*
BDF
BGFK
NGJKL
*/
    return 0;
}

关于c - 使用 4-7 个字母在文本文件中查找整个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21263098/

相关文章:

c - 如何从 C 字符串中删除所有出现的给定字符?

javascript - 如果我的字符串测试函数的输入为空,则返回 false

java - 解释参数的方法

windows - 如何回复快速 javascript 测试

python字符串将多个数组表示为numpy数组

python - Tkinter,Windows : How to view window in windows task bar which has no title bar?

windows - JMeter:为什么在 Windows 中录制的脚本在 Ubuntu 上不起作用?

C:最小和最大输出

c - 为什么我不能通过这段代码得到正确的输出?

c - 当其他宏引发名称冲突时,如何使用其他宏定义宏