Tushar Tushar - 3 months ago 15
MySQL Question

How to emulate MySQL SUBSTRING_INDEX() in scala?

How can I emulate MySQL function SUBSTRING_INDEX() in scala using scala string functions?

For example
MySQL:

SELECT SUBSTRING_INDEX('This is test number one', ' ', 3);


returns
This is test


How to achieve same in scala?

Answer

I don't get this either. This is a bit simpler solution that works as desired.

object Main {
  def main(args: Array[String]): Unit = {
    val str = "this is a string"
    val substring = takeWords(str, ' ', 3)
    println(substring) // yields "this is a"
  }

  def takeWords(s: String, splitAt: Char, n: Int): String = {
    s.split(splitAt) take n mkString(" ") //or whatever separator you need
  }
}
Comments