Scala program to count vowels in a string

1. Introduction

Counting vowels in a string is a common string manipulation operation. Vowels in the English alphabet are 'a', 'e', 'i', 'o', and 'u'. In this blog post, we'll explore a Scala program that counts the number of vowels in a given string.

2. Program Steps

1. Set up the Scala environment.

2. Create an object to house the main function.

3. Within the main function, define a string.

4. Define a function to count the vowels in the string.

5. Print the count of vowels.

6. Run the program.

3. Code Program

object VowelCounterApp {
  def main(args: Array[String]): Unit = {
    val inputString = "HelloScalaProgramming"  // string in which vowels will be counted
    // Count the vowels in the string
    val vowelCount = countVowels(inputString)

    println(s"String: $inputString")
    println(s"Number of vowels: $vowelCount")

  // Function to count vowels in a string
  def countVowels(str: String): Int = {
    val vowels = Set('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
    str.count(vowels contains _)


String: HelloScalaProgramming
Number of vowels: 7


1. The program starts within an object named VowelCounterApp. In Scala, the main method, which serves as the program's entry point, is housed inside an object.

2. We define a string inputString that we intend to examine for vowels.

3. We've defined a function countVowels which calculates the number of vowels in a string. Inside this function, a set of vowels (both lowercase and uppercase) is defined.

4. The count method provided by Scala's String class is used along with the defined vowel set to count the vowels in the input string.

5. The program then prints the input string and the count of vowels present in it.

6. When executed, the program displays the string and the count of vowels it contains.