2017-02-26 66 views
0

我正在嘗試處理任務。這個想法是獲得一串字符串和一個文件流。我需要在文件中查找這些字符串,並計算這些字符串的出現次數。使用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。

對此提出建議?

+2

'(*(strings + i))'請不要。有索引。 – wildplasser

+0

@wildplasser我的字面意思是要寫出幾乎相同的東西,然後才意識到你已經打敗了我:P –

+0

我是C新手。是否違反風格指南?它應該給出相同的輸出,對嗎? –

回答

1

strstr(str, strings[i])返回指向字符串中某個位置的指針。您應該可以遞增該指針(str++)並將其直接傳遞迴strstr(),每次遞增計數,如果strstr()返回NULLstr命中空字符,則結束循環。

它應該看起來像這樣。我沒有測試過這個;但是由於這是你的作業,如果它不能正常工作/編譯,我會把它留給你去調試。這意味着我將不會這麼做所有爲你的工作......

;-)

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++; 
     } 
    } 
    } 
} 
0

要在當前行數的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) 
     } 
    } 
} 
相關問題