我正在嘗試處理任務。這個想法是獲得一串字符串和一個文件流。我需要在文件中查找這些字符串,並計算這些字符串的出現次數。使用fgets和strstr在C中查找和計算字符串
我想我已經得到了基本的循環。唯一的問題是,當我在行中找到一個字符串時,我想從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。
對此提出建議?
'(*(strings + i))'請不要。有索引。 – wildplasser
@wildplasser我的字面意思是要寫出幾乎相同的東西,然後才意識到你已經打敗了我:P –
我是C新手。是否違反風格指南?它應該給出相同的輸出,對嗎? –