Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

How to find the sentence with the greatest number of words

Ravi

Overview

In this Answer, we’ll learn how to find the sentence with the greatest number of words in an array of sentences.

For example, let’s consider we have an array that contains the following three sentences:

  1. “sam and john love educative”,

  2. “We all think so too”,

  3. “this is great thanks very much”

The output that we expect to receive is 66, which is the number of words in the third sentence in the array—the one with the greatest number of words in it.

Solution

The assumption that we make in the solution below is that a single space separates two words in a sentence.

The simple solution to the problem above is as follows:

  1. Count the number of spaces in every sentence.
  2. Find out which sentence has the largest number of spaces, and add one to the number of spaces in this sentence. This will give us the number of words in the sentence with the greatest number of words.

Code

import java.util.Arrays;
import java.util.stream.Stream;

class Main {
    public static int mostWordsFound(String[] sentences) {
        return 1 + Stream.of(sentences)
                .mapToInt(sentence -> (int) sentence.chars().filter(character -> character == ' ').count())
                .max()
                .getAsInt();
    }

    public static void main(String[] args) {
        String[] sentences = {"sam and john love educative", "We all think so too", "this is great thanks very much"};
        int count = mostWordsFound(sentences);
        System.out.println("Array of sentences - " + Arrays.toString(sentences));
        System.out.println("The max number of words found in any sentence is " + count);

    }
}

Explanation

  • Lines 5–10: We define a function called mostWordsFound. With this function, we count the number of single spaces in a sentence using the mapToInt function. We then find out the maximum value, add one to it, and return this value.
  • Lines 13: We define an array of sentences called sentences.
  • Line 14: We invoke the mostWordsFound() method on our array.
  • Line 15: We print the sentences array.
  • Line 16: We print the number of words in the sentence with the greatest number of words.

Refer What is the Stream.mapToInt() method in Java? to learn more about mapToInt().

RELATED TAGS

javascript
RELATED COURSES

View all Courses

Keep Exploring