String Functions in Scala

The standard library’s String class provides many useful string-related functions. Here are some examples to give you a sense of the available operations.

object StringFunctions {
  // We alias println to a shorter name as we'll use it a lot below.
  val p = println _

  def main(args: Array[String]): Unit = {
    // Here's a sample of the functions available for Strings.
    // In Scala, these are methods on the String object itself,
    // so we can call them directly on the string.

    p("Contains:  " + "test".contains("es"))
    p("Count:     " + "test".count(_ == 't'))
    p("StartsWith:" + "test".startsWith("te"))
    p("EndsWith:  " + "test".endsWith("st"))
    p("IndexOf:   " + "test".indexOf('e'))
    p("Join:      " + List("a", "b").mkString("-"))
    p("Repeat:    " + "a" * 5)
    p("Replace:   " + "foo".replace("o", "0"))
    p("Replace:   " + "foo".replaceFirst("o", "0"))
    p("Split:     " + "a-b-c-d-e".split("-").toList)
    p("ToLower:   " + "TEST".toLowerCase)
    p("ToUpper:   " + "test".toUpperCase)
  }
}

When you run this program, you’ll see:

$ scala StringFunctions.scala
Contains:  true
Count:     2
StartsWith:true
EndsWith:  true
IndexOf:   1
Join:      a-b
Repeat:    aaaaa
Replace:   f00
Replace:   f0o
Split:     List(a, b, c, d, e)
ToLower:   test
ToUpper:   TEST

In Scala, many of these operations are methods on the String class itself, rather than functions in a separate package. This allows for a more object-oriented style of programming.

Also, Scala provides some additional convenience methods. For example, instead of a separate Repeat function, Scala allows you to multiply a string by a number to repeat it.

The mkString method on collections (like List) is used to join elements, which is equivalent to the Join function in some other languages.

You can find more string operations in the Scala documentation for the String class.