Scala program to count the number of words in a sentence

1. Introduction

Counting the number of words in a sentence is a common task in text processing and analysis. Given a sentence like "Hello World from Scala", the word count is 4. In this post, we will demonstrate a Scala program that counts the number of words in a given sentence.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Define the sentence whose words need to be counted.

4. Implement a function to compute the word count.

5. Invoke the word-count function and display the result.

6. Run the program.

3. Code Program

object WordCountApp {
  def main(args: Array[String]): Unit = {
    // Define the sentence
    val sentence = "Hello World from Scala"

    println(s"Counting the number of words in the sentence: '$sentence'")

    // Calculate and print the word count using the countWords function
    val count = countWords(sentence)
    println(s"\nThe number of words in the sentence is: $count")
  }

  // Function to determine the number of words in a sentence
  def countWords(s: String): Int = {
    s.split("\\s+").length
  }
}

Output:

Counting the number of words in the sentence: 'Hello World from Scala'
The number of words in the sentence is: 4

Explanation:

1. We initiate with an object named WordCountApp. In Scala, the main method, which serves as the entry point of the program, is situated within an object.

2. Inside the main function, we establish a value sentence which represents the input sentence we wish to process.

3. The program then informs the user about the sentence that's being analyzed.

4. The countWords function determines the word count of a given sentence. It uses the split method to divide the sentence based on spaces, then checks the length of the resulting array, which signifies the word count.

5. The main function calls the countWords method to retrieve the word count and subsequently displays this count.

6. The output first displays the processed sentence and then presents its word count.


Comments