Word Length SBT

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Q.

Write scala code to find the length of each


words from the array. Write a function to find the
length of each word and return the word with
highest length .

import scala.io.StdIn

object WordLength {

def main(args: Array[String]): Unit = {

println("Enter words separated by spaces:")

val input = StdIn.readLine()

// Split the input string into an array of words

val words = input.split("\\s+")

// Find the length of each word

val wordLengths = words.map(word => (word, word.length))

// Print the length of each word

println("Word lengths:")

wordLengths.foreach { case (word, length) =>

println(s"$word: $length")

// Find the word with the highest length

val longestWord = findLongestWord(words)

println(s"\nThe longest word is: $longestWord")

}
// Function to find the word with the highest length
def findLongestWord(words: Array[String]): String = {

words.maxBy(_.length)

Output-

You might also like