This page contains a collection of over 100 Scala String examples, including string functions, format specifiers, and more. I don’t provide too many details about how things work in these examples; this is mostly just a collection of examples that can be used as a Scala String reference page or cheat sheet. (I do show the output of most examples.)

The style used in this lesson

First, here are some basic uses of the Scala String class to help demonstrate the style I’ll use in this lesson:

val hello = "Hello" hello(0) // "H" hello(1) // "e" hello.length // 5 hello.foreach(print) // Hello hello.drop(2) // llo hello.take(2) // He hello.take(2).toLowerCase // he

As shown, I’ll demonstrate how to call a method and then show its result after the // . In the real world you’d assign that result to a variable, like this:

val len = hello.length

String equality

You test string equality with == :

val a = "foo" val b = "foo" val c = "bar" a == b // true a == c // false a == null // false null == a // false

Multiline strings

Multiline strings are created with triple-quotes:

val foo = """This is a multiline String""" val speech = """Four score and |seven years ago""".stripMargin val speech = """Four score and #seven years ago""".stripMargin('#')

Those last two examples both result in this:

Four score and seven years ago

Here’s another example:

val speech = """Four score and |seven years ago |our fathers...""".stripMargin.replaceAll("

", " ")

When it’s executed, speech contains this string:

Four score and seven years ago our fathers...

You can also use single- and double-quotes in multiline strings:

val s = """This is known as a "multiline" string or 'heredoc' syntax"""

String interpolation/substitution

Regarding Scala string substitution/interpolation, there are three built-in interpolators:

s

f

raw

Examples of String substitution/interpolation:

val name = "Joe" val age = 42 val weight = 180.5 // `s` prints "Hello, Joe" println(s"Hello, $name") // `f` prints "Joe is 42 years old, and weighs 180.5 pounds." println(f"$name is $age years old, and weighs $weight%.1f pounds.") // `raw` interpolator prints "foo

bar" println(raw"foo

bar")

Treating a String as a Seq[Char]

A String is a sequence of Char , as these examples demonstrate:

scala> for (c <- "hello") yield c.toUpper res0: String = HELLO scala> "hello".foreach(println) h e l l o scala> "hello".getBytes.foreach(println) 104 101 108 108 111

Using map and for

You can write your own functions to operate on a string. First, create a function that takes a Char and returns whatever type you want it to return:

// a method that takes a Char and returns a Char def toLower(c: Char): Char = (c.toByte+32).toChar

Then you can use that function with map or for/yield :

scala> "HELLO".map(toLower) val res0: String = hello scala> for (c <- "HELLO") yield toLower(c) val res1: String = hello

A function that takes a Char as input and returns Unit can be used with foreach :

scala> def printIt(c: Char): Unit = println(c) def printIt(c: Char): Unit scala> "HAL".foreach(c => printIt(c)) H A L scala> "HAL".foreach(printIt) H A L

Regular expressions

Add .r to the end of a string to create a regular expression:

// create a regex with '.r' val numPattern = "[0-9]+".r // Regex = [0-9]+ // use the regex on `address` val address = "123 Main Street" // "123 Main Street" val match1 = numPattern.findFirstIn(address) // Some(123)

You can also use the Regex class:

// create a regex with Regex class import scala.util.matching.Regex val numPattern = new Regex("[0-9]+") // Regex = [0-9]+ 222 val address = "123 Main Street Unit 639" // "123 Main Street Unit 639" // `findAllIn` returns an iterator val matches = numPattern.findAllIn(address) // non-empty iterator // force the result to a sequence val matches = numPattern.findAllIn(address).toSeq // Stream(123, ?) val matches = numPattern.findAllIn(address).toArray // Array(123, 639) val matches = numPattern.findAllIn(address).toList // List(123, 639)

These examples show how to replace string content using regular expressions:

val regex = "[0-9]".r // Regex = [0-9] regex.replaceAllIn("123 Main Street", "x") // "xxx Main Street" "123 Main Street".replaceAll("[0-9]", "x") // "xxx Main Street" "Hello world".replaceFirst("l", "e") // "Heelo world" "99 Luft Balloons".replaceAll("9", "1") // "11 Luft Balloons" "99 Luft Balloons".replaceFirst("9", "1") // "19 Luft Balloons"

These examples show how to extract the parts of a string you want with regular expression groups:

// create a regex scala> val pattern = "([A-Za-z]+) (\\d+), (\\d+)".r pattern: scala.util.matching.Regex = ([A-Za-z]+) (\d+), (\d+) // apply the regex to a string scala> val pattern(month, day, year) = "June 22, 2018" month: String = June day: String = 22 year: String = 2018

Transforming arrays to a String

These example demonstrate how to transform an array to a string using mkString :

val a = Array(1,2,3) a.mkString // "123" a.mkString(",") // "1,2,3" a.mkString(" ") // "1 2 3" a.mkString("(", ",", ")") // "(1,2,3)"

This example shows how to use a prefix, suffix, and separator with mkString :

scala> val numbers = Array(1,2,3) numbers: Array[Int] = Array(1, 2, 3) scala> numbers.mkString("[", ",", "]") res0: String = [1,2,3]

distinct, intersect, and diff

These examples demonstrate the distinct , intersect , and diff methods:

// distinct "hello world".distinct // "helo wrd" // intersect val a = "Hello" val b = "World" a intersect b // "lo" b intersect a // "ol" // diff val a = "Four score and six years ago" val b = "Four score and seven years ago" a diff b // "ix" b diff a // "vene"

Many String method examples

Finally, here’s a large collection of examples of string methods. First, you’ll need a few sample strings to work with:

val fbb = "foo bar baz" val foo = "foo"

Here are examples of most of the methods available to a String :

foo * 3 // foofoofoo fbb.capitalize // Foo bar baz fbb.collect{case c > 'b' => c} // TODO takes a partial function // returns an Int indicating if `this` is greater than `that` fbb.compare("doo") // 2 (this > that) fbb.compare(fbb) // 0 (this == that) fbb.compare("goo") // -1 (this < that) fbb.compareTo("doo") // 2 (this > that) fbb.compareTo(fbb) // 0 (this == that) fbb.compareTo("goo") // -1 (this < that) fbb.compareToIgnoreCase("doo") // 2 (this > that) fbb.compareToIgnoreCase("FOO BAR BAZ") // 0 (this == that) fbb.compareToIgnoreCase("goo") // -1 (this < that) fbb.count(_ == 'a') // 2 fbb.diff("foo") // " bar baz" fbb.distinct // fo barz fbb.drop(4) // bar baz fbb.dropRight(2) // foo bar b fbb.dropWhile(_ != ' ') // " bar baz" fbb.endsWith("baz") // true fbb.filter(_ != 'a') // foo br bz fbb.foldLeft("")(_.toUpperCase + _.toLower) // FOO BAR BAz fbb.fold // TODO fbb.foreach(println(_)) // prints one character per line fbb.foreach(println) // prints one character per line // use the interpolators instead of this String.format("Hi, %s", "world") // "Hi, world" fbb.getBytes.foreach(println) // prints the byte value of each character, one value per line fbb.head // f fbb.headOption // Some(f) fbb.indexOf('a') // 5 fbb.isEmpty // false fbb.lastIndexOf('o') // 2 fbb.length // 11 fbb.map(_.toUpper) // FOO BAR BAZ fbb.map(_.byteValue) // Vector(102, 111, 111, 32, 98, 97, 114, 32, 98, 97, 122) fbb.min // " " fbb.mkString(",") // f,o,o, ,b,a,r, ,b,a,z fbb.mkString("->", ",", "<-") // ->f,o,o, ,b,a,r, ,b,a,z<- fbb.nonEmpty // true fbb.par // a parallel array, ParArray(f, o, o, , b, a, r, , b, a, z) fbb.partition(_ > 'e') // (foorz, " ba ba") // a Tuple2 fbb.reduce // TODO fbb.replace('o', 'x') // fxx bar baz fbb.replace("o", "x") // fxx bar baz fbb.replaceAll("o", "x") // fxx bar baz fbb.replaceFirst("o", "x") // fxo bar baz fbb.reverse // zab rab oof fbb.size // 11 fbb.slice(0,5) // foo b fbb.slice(2,9) // o bar b // NOTE: `sortBy` is complicated, this is a simple example fbb.sortBy(c => c) // " aabbfoorz" fbb.sortWith(_ < _) // " aabbfoorz" fbb.sortWith(_ > _) // "zroofbbaa " fbb.sorted // " aabbfoorz" fbb.span(_ != 'a') // ("foo b", "ar baz") fbb.split(" ") // Array(foo, bar, baz) fbb.splitAt(3) // (foo," bar baz") fbb.substring(0,3) // "foo" fbb.substring(0,4) // "foo " fbb.substring(1,5) // "oo b" fbb.substring(1,6) // "oo ba" fbb.substring(0, fbb.length-1) // "foo bar ba" fbb.substring(0, fbb.length) // "foo bar baz" fbb.tail // oo bar baz fbb.take(3) // foo fbb.takeRight(3) // baz fbb.takeWhile(_ != 'r') // foo ba fbb.toArray // Array(f, o, o, , b, a, r, , b, a, z) fbb.toBuffer // ArrayBuffer(f, o, o, , b, a, r, , b, a, z) fbb.toList // List(f, o, o, , b, a, r, , b, a, z) fbb.toSet // Set(f, a, , b, r, o, z) fbb.toStream // Stream[Char] = Stream(f, ?) fbb.toLowerCase // foo bar baz fbb.toUpperCase // FOO BAR BAZ fbb.toVector // Vector(f, o, o, , b, a, r, , b, a, z) fbb.trim // "foo bar baz" fbb.view // SeqView[Char,String] = SeqView(...)

(Note that a String isn’t a great example for some of those methods.)

zip and zipWithIndex require a little more room for output, so I show them here separately:

fbb.zip(0 to 10) // results in: Vector((f,10), (o,11), (o,12), ( ,13), (b,14), (a,15), (r,16), ( ,17), (b,18), (a,19), (z,20)) fbb.zipWithIndex // results in: Vector((f,0), (o,1), (o,2), ( ,3), (b,4), (a,5), (r,6), ( ,7), (b,8), (a,9), (z,10))