Counting words in a string - c programming

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

    #include 
    
    int wordcount (char *string){
    
        int n = 0; 
    
        char *p = string ;
        int flag = 0 ;
    
        while(isspace(*p)) p++;
    
    
        while(*p){
            if(!isspace(*p)){
                if(flag == 0){
                    flag = 1 ;
                    n++;
                }
            }
            else flag = 0;
            p++;
        }
    
        return n ;
    }
    
    
    int main(int argc, char **argv){
    
        printf("%d\n" , wordcount("    hello  world\nNo matter how many newline and spaces"));
        return 1 ;
    }
    

提交回复
热议问题