String-interview question 1: How many words are included in a line of Characters ?, Question line
The number of words can be determined by the number of occurrences of spaces (several consecutive spaces are used as the occurrence of one space; spaces starting with a line are not counted ). If it is determined that a character is not a space, and the character before it is a space, it indicates "a new word starts". In this case, the word counter is added with 1 ,; if the current character is a non-space character and the previous character is a non-space character, it means that the word continues, and the count value should not be accumulated. Whether the preceding character is a space can be seen from the word value. If word is equal to 0, it indicates that the first character is a space. If word is 1, it means that the preceding character is not a space.
1 package com. mianshi. easy; 2 public class Test1 {3 4 public static int wordCount (String s) {5 int word = 0; 6 int count = 0; 7 for (int I = 0; I <s. length (); I ++) {8 if (s. charAt (I) = '') {9 word = 0; 10} else if (word = 0) {11 word = 1; 12 count ++; 13} 14} 15 return count; 16} 17 18 public static void main (String [] args) {19 20 String s = "It is a good day! "; 21 int I = Test1.wordCount (s); 22 System. out. println (s +" Number of words: "+ I); 23} 24}
Result:
It is a good day! Number of words: 5
It is likely to be written as: else if (s. charAt (I )! = ''& Word = 0.
The number of times word is equal to a flag.