Counting words in a string - c programming

后端 未结 12 2168
有刺的猬
有刺的猬 2020-12-07 01:52

I need to write a function that will count words in a string. For the purpose of this assignment, a \"word\" is defined to be a sequence of non-null, non-whitespace characte

12条回答
  •  鱼传尺愫
    2020-12-07 02:27

    Here is one solution. This one will count words correctly even if there are multiple spaces between words, no spaces around interpuncion symbols, etc. For example: I am,My mother is. Elephants ,fly away.

    #include 
    #include 
    #include 
    #include 
    
    
    int countWords(char*);
    
    
    int main() {
        char string[1000];
        int wordsNum;
    
        printf("Unesi nisku: ");
        gets(string);  /*dont use this function lightly*/
    
        wordsNum = countWords(string);
    
        printf("Broj reci: %d\n", wordsNum);
    
        return EXIT_SUCCESS;
    }
    
    
    int countWords(char string[]) {
        int inWord = 0,
            n,
            i,
            nOfWords = 0;
    
        n = strlen(string);
    
        for (i = 0; i <= n; i++) {
            if (isalnum(string[i]))
                inWord = 1;
            else
                if (inWord) {
                    inWord = 0;
                    nOfWords++;
                }
        }
    
        return nOfWords;
    }
    

提交回复
热议问题