2012-10-10 32 views
3

我在字符串中計算字詞出現次數。對於字符串S,我需要顯示每個單詞以及該單詞在字符串中出現的次數。在字符串中計數字詞出現

例:

string = ";! one two, tree foor one two !:;" 

結果:

one: 2 
two: 2 
tree: 1 
foor: 1 

這裏是我的代碼,但它沒有返回正確的計數:

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 

int count_word(char * mot, char * text) { 
    int n = 0; 
    char *p; 

    p = strstr(text, mot); 

    while (p != NULL) { 
    n++; 
    p = strstr(p + 1, mot); 
    } 

    return n; 
} 

void show_all_words(char * text) { 
    char * p = strtok(text, " .,;-!?"); 

    while (p != NULL) { 
     printf ("%s : %d\n", p, count_word(p, text)); 
     p = strtok(NULL, " .,;-!?"); 
    } 
} 

int main(char *argv[]) { 

    char text[] = ";! one two, tree foor one two !:;"; 
    show_all_words(&text); 

    return (EXIT_SUCCESS); 
}; 

它的返回:

one : 1 
two : 0 
tree : 0 
foor : 0 
one : 1 
two : 0 
: : 0 
+5

你問C語言問題還是C++問題?它們是不同的語言,並且標籤不能互換使用。 – meagar

+0

我修復了這個問題並刪除了C++標籤,我問了一個C問題。 – Alex

回答

3

功能strtok更改其參數。您可以通過複製字符串來解決問題,在一個副本上調用strtok,在另一個副本上調用count_word

另外,請注意不要輸出兩次相同單詞的計數。

int count_word(char * mot, char * text, int offset) { 
    int n = 0; 
    char *p; 

    p = strstr(text, mot); 
    assert(p != NULL); 
    if (p - text < offset) 
     return -1; // if the word was found at an earlier offset, return an error code 

    while (p != NULL) { 
    n++; 
    p = strstr(p + 1, mot); 
    } 

    return n; 
} 

void show_all_words(char * text) { 
    char *text_rw = strdup(text); // make a read-write copy to use with strtok 
    char * p = strtok(text_rw, " .,;-!?"); 

    while (p != NULL) { 
     int offset = p - text; // offset of the word inside input text 
     int count = count_word(p, text, offset); 
     if (count != -1) // -1 is an error code that says "already looked at that word" 
      printf ("%s : %d\n", p,); 
     p = strtok(NULL, " .,;-!?"); 
    } 
    free(text_rw); // delete the copy 
} 
1

您應該改變方法。 您可以使用數組來存儲每個單詞的首次出現的索引以及出現次數。 只有一個人在字符串中行進,但更多的人在輔助數組中行進,以檢查當前單詞是否已經被計數。

我希望對你有用。

+0

由於你的字符串變得很大,爲每個單詞重新計算將是昂貴的方式。你想要統計一切,然後報告。最好將所有的令牌放入一個數組,然後按字母順序對數組進行排序,然後進行計數。 –

相關問題