Counting words in a string - c programming

后端 未结 12 2139
有刺的猬
有刺的猬 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:18

    bool isWhiteSpace( char c )
    {
        if( c == ' ' || c == '\t' || c == '\n' )
            return true;
        return false;
    }
    
    int wordCount( char *string )
    {
        char *s = string;
        bool inWord = false;
        int i = 0;
    
        while( *s )
        {
            if( isWhiteSpace(*s))
            {
                inWord = false;
                while( isWhiteSpace(*s) )
                    s++;
            }
            else
            {
                if( !inWord )
                {
                    inWord = true;
                    i++;
                }
                s++;
            }
        }
    
        return i;
    }
    

提交回复
热议问题