簡體   English   中英

用於計算字符串中單詞出現次數的C代碼

[英]C code for counting number of occurrences of a word in string

我正在嘗試編寫一個接受字符串和單詞的函數,並輸出它出現在字符串中的次數。

我的出價:

int CountWord(char *s, char *word) {
    char first = word[0];
    int i, j, count = 0;
    while (s[i] != '\0') {
        if (s[i] == first)
            for (j = 1; (s[i+j] == word[j]) && (word[j] != '\0') && (s[i+j] != '\0'); ++j) {
                if (word[j] == '\0')
                    ++count;
        }
    }
    return count;
}

問題:它不適用於“代碼塊”。

在此先感謝您的幫助。

您的代碼中存在多個問題:

  • 你不初始化i
  • 你不增加i
  • for循環中的測試(word[j] != '\\0')阻止了計數代碼的執行。
  • 在字符串末尾找不到匹配項
  • 如果word為空字符串,則計數將不正確。
  • 在某些體系結構上, int可能沒有非常長的字符串所需的范圍。

這是更正的版本:

size_t CountWord(const char *s, const char *word) {
    char first = word[0];
    size_t i, j, count = 0;

    if (first == '\0')
        return strlen(s) + 1;

    for (i = 0; s[i] != '\0'; i++) {
        if (s[i] == first) {
            for (j = 1; word[j] != '\0' && s[i + j] == word[j]; j++)
                continue;
            if (word[j] == '\0')
                count++;
        }
    }
    return count;
}

請注意,此實現將為CountWord("aaa", "aa")返回2 ,這可能是也可能不是預期的結果。 規范必須准確,並告訴您是要計算word重復出現還是僅對不重復的匹配進行計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM