String-interview question 1: How many words are included in a line of Characters ?, Question line

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.