我真的很难理解字符数组如何在C中工作。这看起来应该很简单,但是我不知道要使用什么函数或如何使用它。
我希望用户输入一个字符串,并且要遍历文本文件,将该字符串与文件中每行的第一个单词进行比较。
这里的“单词”是指由非空格字符组成的子字符串。
非常感谢您的帮助!
编辑:更清楚地说,我想输入一个输入并在文本文件形式的数据库中搜索它。我知道如果它在数据库中,它将是一行的第一个字,因为这是如何格式化数据库的。我想我可以遍历数据库的每个单词,但这似乎效率较低。
在数据库中找到输入之后,我需要访问跟在它后面的两个词(在同一行上)以实现程序的最终目标(本质上是计算性的)
这是一些可以满足您要求的代码。我认为它将帮助您更好地了解字符串函数的工作方式。注意-对于输入和文本文件的条件调整情况,我没有做很多假设,因此有很多代码可以从输入中删除空格,并检查匹配是否确实是“第一个单词”,而不是“第一个单词的第一部分”。因此,此代码不会将输入“ hello”与“ helloworld 123 234”行匹配,但将与“ helloworld 123 234”行匹配。还要注意,它目前区分大小写。
#include <stdio.h>
#include <string.h>
int main(void) {
char buf[100]; // declare space for the input string
FILE *fp; // pointer to the text file
char fileBuf[256]; // space to keep a line from the file
int ii, ll;
printf("give a word to check:\n");
fgets(buf, 100, stdin); // fgets prevents you reading in a string longer than buffer
printf("you entered: %s\n", buf); // check we read correctly
// see (for debug) if there are any odd characters:
printf("In hex, that is ");
ll = strlen(buf);
for(ii = 0; ii < ll; ii++) printf("%2X ", buf[ii]);
printf("\n");
// probably see a carriage return - depends on OS. Get rid of it!
// note I could have used the result that ii is strlen(but) but
// that makes the code harder to understand
for(ii = strlen(buf) - 1; ii >=0; ii--) {
if (isspace(buf[ii])) buf[ii]='\0';
}
// open the file:
if((fp=fopen("myFile.txt", "r"))==NULL) {
printf("cannot open file!\n");
return 0;
}
while( fgets(fileBuf, 256, fp) ) { // read in one line at a time until eof
printf("line read: %s", fileBuf); // show we read it correctly
// find whitespace: we need to keep only the first word.
ii = 0;
while(!isspace(fileBuf[ii]) && ii < 255) ii++;
// now compare input string with first word from input file:
if (strlen(buf)==ii && strstr(fileBuf, buf) == fileBuf) {
printf("found a matching line: %s\n", fileBuf);
break;
}
}
// when you get here, fileBuf will contain the line you are interested in
// the second and third word of the line are what you are really after.
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句