我是 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/