簡體   English   中英

計算字符串中的單詞

[英]Count words from a string

while( (ch = fgetc( infile )) != EOF )
    if(ch ==' ') words++;

效果很好,但是如果字符串中有空行,我們應該如何檢測這些行並正確地計算出單詞數呢?

您的代碼不計算單詞,而是計算空格。 在許多情況下,這兩種計數可能會有所不同-例如,當單詞被一個以上的空格分隔時。

您需要更改邏輯,以便在看到屬於單詞的字符時設置一個布爾標志“我在單詞中”,並且在看到空白字符(空格,制表符或換行符):

if (isspace(ch)) {
    if (sawWordFlag) {
        words++;
        sawWordFlag = false;
    }
}

一種檢測字符是否屬於單詞的方法是在其上調用isalnum isalnumisspace函數都要求您包含<ctype.h>標頭。

因此sscanf已經滿足了您的需要,它將在包含制表符和換行符的字符串之前占用任意數量的空格。 該算法也適用於前導或尾隨空格。

int words = 0;
int i = 0;

while(sscanf(inFile, "%*s%n", &i) != EOF){
    inFile += i;
    words++;
}

sscanf具有多種用途,您可以按以下方式輕松讀出每個單詞:

int words = 0;
int size = strlen(inFile);

if(size > 0){
    char* word = (char*)malloc((size + 1) * sizeof(char));

    for(int i = 0; sscanf(sentence, "%s%n", word, &i) > 0; sentence += i){
        // Do what you want with word here
        words++;
    }
    free(word);
}
char prev = 'x'; // anything but space
while((ch == fgetc(infile)) != EOF)
{
    if(ch == ' ' && ch == prev)
        continue;
    else if(ch == ' ' && ch != prev)
        words++;
    prev = ch;
}

暫無
暫無

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

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