How to get the last word from a string in Scala

2 Answers

0 votes
val s = "Scala from small scripts to large multiplatform applications"

val words = s.split(" ")

val lastWord = words.last

println(lastWord)  

 
 
/*
run:
   
applications
 
*/

 



answered Jan 4, 2025 by avibootz
0 votes
object Main {
  def getLastWord(input: String): String = {
    // Trim leading/trailing whitespace
    val trimmed = input.trim

    // If empty after trimming, return empty string
    if (trimmed.isEmpty) ""
    else {
      // Split on whitespace and return the last element
      trimmed.split("\\s+").lastOption.getOrElse("")
    }
  }

  def main(args: Array[String]): Unit = {
    val tests = Seq(
      "vb.net javascript php c c++ python c#",
      "",
      "c#",
      "c c++ java ",
      "  "
    )

    tests.zipWithIndex.foreach { case (t, i) =>
      println(s"${i + 1}. ${getLastWord(t)}")
    }
  }
}


/*
run:

1. c#
2. 
3. c#
4. java
5. 

*/

 



answered Mar 27 by avibootz
...