SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Conditional Execution
Exercise:
Exercises
Question:15 | ISBN:9780136091813 | Edition: 2

Question

Write a method called wordCount that accepts a String as its parameter and returns the number of words in the String. A word is a sequence of one or more nonspace characters (any character other than ' '). For example, the call wordCount("hello") should return 1, the call wordCount("how are you?") should return 3, the call wordCount(" this string has wide spaces ") should return 5, and the call wordCount(" ") should return 0.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer



public class CountWords {

    public static int wordCount(String string) {

        int count = 0;

        // \\s+ regex, split the words based on white spaces
        // split method takes the regex as an argument
        String[] var = string.split("\\s+");

        // if it is  greater than zero count that as word
        for (String str : var) {
            if (str.length() > 0)
                count++;
        }

        
        return count;
    }

    public static void main(String args[]) {

        String string = "blackholes are always fascinates me;; ";
        int numOfWords = CountWords.wordCount(string);
        System.out.println(string+"contains " +numOfWords+ " words");
    }

}
Output:


blackholes are always fascinates me;; contains 5 words

 

0 0

Discussions

Post the discussion to improve the above solution.