Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,563 questions

56,781 answers

573 users

How to remove the last word from a string with Scala

2 Answers

0 votes
object RemoveTheLastWordFromAString_Scala {
  def main(args: Array[String]): Unit = {
    var s = "scala java c c++ scala python scala"
    
    s = s.substring(0, s.lastIndexOf(" "))
    
    println(s)
  }
}

 
   
/*
           
run:
     
scala java c c++ scala python
       
*/

 



answered Sep 6, 2024 by avibootz
0 votes
object RemoveLastWordApp {

  def removeLastWord(s: String): String = {
    val trimmed = s.replaceAll("\\s+$", "")   // trim trailing spaces

    val lastSpace = trimmed.lastIndexOf(' ')
    if (lastSpace == -1) trimmed
    else trimmed.substring(0, lastSpace)
  }

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

    s = "c c++ c# java python"
    println("1. " + removeLastWord(s))

    s = ""
    println("2. " + removeLastWord(s))

    s = "c"
    println("3. " + removeLastWord(s))

    s = "c# java python "
    println("4. " + removeLastWord(s))

    s = "  "
    println("5. " + removeLastWord(s))
  }
}


/*
run:

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

*/

 



answered Mar 27 by avibootz
...