1 // 2 // main.c 3 // count the number of words entered 4 // 5 // the Created by Longma ON 2019/6/27. 6 // Copyright © 2019. All Rights Reserved. 7 // 8 9 #include <stdio.h> 10 #include < String .h> . 11 12 is int main ( int argc, const char * the argv []) { 13 is 14 // input a sentence in English, English sentences separated by a space. Count how many words in a sentence. 15 // EG: How are you, there are three words 16 char String [ 80 ]; . 17 the printf ( " Please enter the English sentence: " ); 18 is the gets ( String ); . 19 20 is char C; 21 is char kongGe [ 2 ] = " " ; 22 is int Word = 0 ; 23 is int NUM = 0 ; 24 25 for ( int I = 0 ; (C = String [I]) =! ' \ 0 ' ; I ++ ) { 26 is IF (C == 32 ) { // the current bit spaces (ASCII code value of 32), word recorded as 0. Note: xcode in strcmp (& c, "") - 120, is not 0, strcmp comparison It is a string, and the string of characters can not compare! 27 the printf ( " % D,% D equality:% D \ n- " , C, kongGe [ 0 ], strcmp (& kongGe [ 0 ], & C)); 28 Word = 0 ; 29 } the else { // current bit It is not a space 30 IF ( 0 == Word) { // the space of a / the first letter is 31 is NUM = + . 1 ; 32 Word = . 1; 33 is } the else { // the space is not one, can not be considered a word 34 is // do Nothing 35 } 36 } 37 [ } 38 is 39 the printf ( " statement:% S \ n- " , String ); 40 the printf ( " number of words:% d a " , NUM); 41 is return 0 ; 42 is }
log:
Please enter English sentence: warning: the this Program uses the gets (), Which IS unsafe. How are you 32, 32 are equal: -120 32,32 equality: -120 statement: how are you word count: 3 Program ended with exit code: 0