How many words are updated in a string? C language, Tan haoqiang, example 6.8
For example, 6.8 enter a line of characters and count the number of words. Separate words with spaces. Original solution: Check the characters one by one from the first character, determines whether the character starts with a new word. To determine whether a new word exists, it is determined by whether a space exists. If a character is not a space and the character before it is a space, it indicates that the new word starts.
# Include <stdio. h> # include <stdlib. h> int main (void) {char string [81]; int I, num = 0, word = 0; char c; gets (string); for (I = 0; (c = string [I])! = '\ 0'; I ++) // continues the loop as long as it is not the character' \ 0' {if (c = '') word = 0; else if (word = 0) {word = 1; num ++ ;}} printf ("There are % d words in the line. \ n ", num); return 0 ;}
New Thinking: The word ends when a character is not a letter. Extends the punctuation in the string.
/*************************************** * ************** 6.8 Count how many wordsPlan: if a charactor is not a letter, and before it there is a letter, count addCREATE ---------------------------- By: Idooi LiuTime: 2015/09/27-1022 ----------------------------------************************************ * *****************/# include <stdio. h> # include <stdlib. h> # include <stdbool. h> bool ifALetter (char charactor ); Int main (void) {int I, number = 0; char stringMe [100]; gets (stringMe); for (I = 0; I <100; I ++) {if (stringMe [I + 1] = '\ 0') // The end loop with the character' \ 0' {if (ifALetter (stringMe [I]) number ++; break;} // determines the last character of a word. The next character is not a letter and the word ends if (ifALetter (stringMe [I]) &! IfALetter (stringMe [I + 1]) number ++;} printf ("There are % d words in the line. \ n ", number); getchar (); return 0 ;}// determines whether the character is a letter bool ifALetter (char x) {if (x> 64 & x <91) | (x> 96 & x <122) return true; else return false ;}