Acronym in Scala
object Acronym {
  def abbreviate(phrase: String): String = raw"[\s-]+".r

This approach starts by defining a Regex pattern using a raw interpolator. The raw interpolator allows using the backslash escape character in a Regex patttern without having to escape the backslash with another backslash. The pattern looks for one or more whitespace or dash characters. A variant ("[ -]+") could look for just spaces or a dash.

The Regex calls its split() method, which splits the input phrase around all matches of the Regex. The resulting Array of words is chained to the map() method, which calls toUpper() on the head of each word and passes the uppercased first character of each word to the mkString() method, which returns all of those characters from the abbreviate() method as a String.

29th May 2024 · Found it useful?