How to get the length of the last word in a string with Scala

1 Answer

0 votes
object Program {
  def lengthOfLastWord(str: String): Int = {
    val words = str.split(" ").toList
    
    words.last.length
  }

  def main(args: Array[String]): Unit = {
    val str = "java c  javascript golang"
    
    println(s"The length of the last word is: ${lengthOfLastWord(str)}")
  }
}


   
/*
           
run:
     
The length of the last word is: 6
       
*/

 



answered Sep 9, 2024 by avibootz
edited Sep 9, 2024 by avibootz
...