[英]Finding and counting strings in C using fgets and strstr
我正在尝试一项任务。 这个想法是获得一个字符串数组和一个文件流。 我需要在文件中查找那些字符串,并计算这些字符串的出现次数。
我想我的基本循环了。 唯一的问题是,当我在行中找到一个字符串时,我想从1 +找到的字符串开始的位置开始再次搜索该字符串(如果出现多次)。
#define LINE_MAX_CHARS 1000
// n = number of strings to be found
// **strings = array of strings to look for in file
void count_occurrences (int n, FILE *file, char **strings) {
char str[LINE_MAX_CHARS]; // buffer
int count = 0;
while (fgets(str, LINE_MAX_CHARS, file) != NULL){ // for each line
for (int i = 0; i < n; i++){ // for each word in line
char *found;
found = (strstr(str, (*(strings + i)))); // search line
if (found != NULL){ // if word found in line
// here, I want str (the buffer) to have its 0-th element to be the element at (found + 1),
// and the 1-st element to be (found + 2) and so on...
i--; // to look for same word in the rest of the line
count = count + 1;
}
}
}
}
另一个问题是我无法测试我的代码。 我只是得到了一个运行的测试程序,告诉我我的代码是否产生正确的输出。
我需要使用fgets和strstr。
有什么建议吗?
strstr(str, strings[i])
返回一个指向字符串中某个位置的指针。 您应该能够递增该指针( str++
)并在循环中将其直接传递回strstr()
,每次递增计数,如果strstr()
返回NULL
或str
击空字符,则结束循环。
它看起来应该像这样。 我还没有测试过 但是,由于这是您的作业,因此如果无法正常工作/编译,我将把它留给您进行调试。 这意味着我不会为您完成所有工作...
;-)
void count_occurrences (int n, FILE *file, char **strings) {
char str[LINE_MAX_CHARS];
int count = 0;
while (fgets(str, LINE_MAX_CHARS, file) != NULL){
for (int i = 0; i < n; i++){
char *pos = str;
while(((pos = strstr(pos, strings[i]) != NULL) && *pos != '\n') {
count++;
pos++;
}
}
}
}
要计算当前行中strings[i]
每一次出现,您必须使用循环,并且必须让strstr
在最后一次出现之后至少开始一个位置。 请参见以下代码:
#define LINE_MAX_CHARS 1000
// n = number of strings to be found
// **strings = array of strings to look for in file
void count_occurrences (int n, FILE *file, char **strings) {
char str[LINE_MAX_CHARS]; // buffer
int count = 0;
while (fgets(str, LINE_MAX_CHARS, file) != NULL){ // for each line
for (int i = 0; i < n; i++){ // for each word in line
char *found = str;
do {
found = strstr(found, strings[i]); // search line
if (found != NULL){ // if word found in line
count = count + 1;
found++;
}
}
while (found)
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.