Problem Description: Statistics a string, string consisting of words, spaces.
Ideas:
One, traverse all characters of the string, set a Boolean variable to determine whether the current is a space or a letter
1#include <stdio.h>2#include <stdbool.h>3#include <string.h>4 5 intCount_words (Char*s)6 {7 intLen=strlen (s);//len holds string length8 BOOLIswhite=true; 9 intI,count=0;//Count is used to count the number of wordsTen for(i=0; i<len;i++) One { A if(* (s+i) = =' ')//the current character is empty - { -Iswhite=true; the}Else if(Iswhite) {//This code is executed to indicate that the current character is not empty and the last character is empty -count++;//number of words +1 -Iswhite=false;//enter a non-whitespace state - } + } - returncount; + } A at intMain () - { - Char* a="I Love you"; -printf"%d", Count_words (a)); -}
Second, traversing all characters of the string, if the current character is not empty, the number of words +1, and then nested a while loop to determine whether the current word is ending
1#include <stdio.h>2#include <string.h>3 4 intCount_words (Char*s)5 { 6 intlen=strlen (s);7 intcount,i;8 for(i=0; i<len;i++)9 {Ten if(* (s+i)! =' '){//If the current code is empty Onecount++;//number of words +1 A while(* (s+i)! =' '&& I<len)//determines whether the current word ends -i++; - } the } - returncount; - } - + intMain () - { + Char* a="I Love you"; Aprintf"%d", Count_words (a)); at}
Two ways to count the number of string words (C language Implementation)