A collection of 100+ Scala String examples

This page contains a collection of over 100 Scala String examples, including strings 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 reference page or cheat sheet. (I do show the output of most examples.)

First, here are some basic uses of the Scala String class to help get us warmed up:

val name = "Alvin"
val fullName = name + " Alexander"  // Alvin Alexander
val fullName = s"$name Alexander"   // Alvin Alexander

name.length                // 5
name.foreach(print)        // Alvin
name.take(2)               // Al
name.take(2).toLowerCase   // al
Back to top

String equality

Test string equality with the == symbol (a method, actually):

val a = "foo"
val b = "foo"
val c = "bar"
a == b       // true
a == c       // false
Back to top

Multiline strings

It’s easy to create multiline strings in Scala:

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('#')

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

// from @SomSnytt an twitter, instead of replaceAll("\n", " ") you can use these:
yourStringHere.lines.mkString(" ")
yourStringHere.lines mkString " "

// use single- and double-quotes in a multiline string
val s = """This is known as a
"multiline" string
or 'heredoc' syntax"""
Back to top

String interpolation/substitution

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

  • s
  • f
  • raw

Examples of String substitution/interpolation:

val name = "Joe"
val age = 42
val weight = 180.5

// prints "Hello, Joe"
println(s"Hello, $name")

// 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
println(raw"foo\nbar")

On a related note, here are some printf formatting characters:

%c  character
%d  decimal (integer) number (base 10)
%e  exponential floating-point number
%f  floating-point number
%i  integer (base 10)
%o  octal number (base 8)
%s  a string of characters
%u  unsigned decimal (integer) number
%x  number in hexadecimal (base 16)
%%  print a percent sign
\%  print a percent sign

You can find more printf details on this page: A printf reference page (cheat sheet).

Back to top

Substrings

val s = "four score"
s.substring(0,3)             // "fou"
s.substring(0,4)             // "four"
s.substring(1,5)             // "our "
s.substring(1,6)             // "our s"
s.substring(0, s.length-1)   // "four scor"
s.substring(0, s.length)     // "four score"
Back to top

Treating a String as an Array[Char]

A String is an array of Char, so:

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
Back to top

Using map and for

Write your own function to operate on a Char, then use ’map’ or ’for’:

// a custom method
def toLower(c: Char):Char = (c.toByte+32).toChar

// map
"HELLO".map(toLower)   // "hello"

// for/yield
for (c <- "HELLO") yield toLower(c)

// pass method to 'foreach'
def printIt(c: Char) { println(c) }
"HAL".foreach(c => printIt(c))
"HAL".foreach(printIt)
Back to top

Regular expressions

Can use .r on a string to create a regular expression. Can also use the Regex class:

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

// create a regex with Regex class
import scala.util.matching.Regex
val numPattern = new Regex("[0-9]+")
val address = "123 Main Street Unit 639"
val matches = numPattern.findAllIn(address)           // non-empty iterator
val matches = numPattern.findAllIn(address).toArray   // Array(123, 639)

“Replacing” string content:

val regex = "[0-9]".r
regex.replaceAllIn("123 Main Street", "x")

"123 Main Street".replaceAll("[0-9]", "x")   // "xxx Main Street"
"Hello world".replaceFirst("H", "J")         // "Jello world"
"99 Luft Balloons".replaceAll("9", "1")      // "11 Luft Balloons"
"99 Luft Balloons".replaceFirst("9", "1")    // "19 Luft Balloons"

Extracting the parts of a String you want (regular expression groups):

val pattern = "([A-Za-z]+) (\\d+), (\\d+)".r
val pattern(month, day, year) = "June 22, 2012"

scala> val pattern = "([A-Za-z]+) (\\d+), (\\d+)".r
pattern: scala.util.matching.Regex = ([A-Za-z]+) (\d+), (\d+)

scala> val pattern(month, day, year) = "June 22, 2012"
month: String = June
day: String = 22
year: String = 2012
Back to top

Transforming arrays to a String

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

How to get a character at a String position:

// the java way (don't do this)
"hello".charAt(0)   // "h"

// the scala way
"hello"(0)          // "h"   
"hello"(1)          // "e"
Back to top

A lot of String method examples

Uppercase, lowercase, and capitalize method examples:

val s = "hello world"
s.toUpperCase    // "HELLO WORLD"
s.toLowerCase    // "hello world"
s.capitalize     // "Hello world"

Distinct, intersect, and diff method examples:

// distinct
"hello world".distinct   // yields "helo wrd"

// intersect
val a = "Alvin"
val b = "Alexander"
a intersect b            // yields "Aln"
b intersect a            // yields "Aln"

// 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"

And now for a lot of examples. First, we’ll need a few sample strings to work with:

val a = "foo bar baz"
val foo = "foo"

A String can be treated as a collection of Char, and that’s what is shown in many of the following examples. I’ve skipped over a few of the collection-related methods because (a) they’re a little harder to show, and (b) I’m running out of time. Here are the String examples:

foo * 3                        // foofoofoo

a.capitalize                   // Foo bar baz
a.collect
a.compare
a.compareTo
a.count(_ == 'a')              // 2
a.diff("foo")                  // " bar baz"
a.distinct                     // fo barz
a.drop(4)                      // bar baz
a.dropRight(2)                 // foo bar b
a.dropWhile(_ != ' ')          // " bar baz"
a.endsWith("baz")              // true
a.filter(_ != 'a')             // foo br bz
a.fold                         // 
a.foreach(println(_))          // prints one character per line
a.foreach(println)             // prints one character per line
a.format                       // 
a.getBytes.foreach(println)    // prints the byte value of each character, one value per line
a.head                         // f
a.headOption                   // Some(f)
a.indexOf('a')                 // 5
a.intersect                    // shown above
a.isEmpty                      // false
a.lastIndexOf('o')             // 2
a.length                       // 11
a.map(_.toUpper)               // FOO BAR BAZ
a.map(_.byteValue)             // Vector(102, 111, 111, 32, 98, 97, 114, 32, 98, 97, 122)
a.min                          // " "
a.mkString(",")                // f,o,o, ,b,a,r, ,b,a,z
a.mkString("->", ",", "<-")    // ->f,o,o, ,b,a,r, ,b,a,z<-
a.nonEmpty                     // true
a.par                          // a parallel array, ParArray(f, o, o,  , b, a, r,  , b, a, z)
a.partition(_ > 'e')           // (foorz, " ba ba")  // a Tuple2
a.reduce                       //
a.replace('o', 'x')            // fxx bar baz
a.replace("o", "x")            // fxx bar baz
a.replaceAll("o", "x")         // fxx bar baz
a.replaceFirst("o", "x")       // fxo bar baz
a.reverse                      // zab rab oof
a.size                         // 11
a.slice(0,5)                   // foo b
a.slice(2,9)                   // o bar b
a.sortBy                       //
a.sortWith(_ < _)              // "  aabbfoorz"
a.sortWith(_ > _)              // "zroofbbaa  "
a.sorted                       // "  aabbfoorz"
a.span                         //
a.split(" ")                   // Array(foo, bar, baz)
a.splitAt(3)                   // (foo," bar baz")
a.substring(4,9)               // bar b
a.tail                         // oo bar baz
a.take(3)                      // foo
a.takeRight(3)                 // baz
a.takeWhile(_ != 'r')          // foo ba
a.toArray                      // Array(f, o, o,  , b, a, r,  , b, a, z)
a.toBuffer                     // ArrayBuffer(f, o, o,  , b, a, r,  , b, a, z)
a.toList                       // List(f, o, o,  , b, a, r,  , b, a, z)
a.toSet                        // Set(f, a,  , b, r, o, z)
a.toStream                     // 
a.toLowerCase                  // foo bar baz
a.toUpperCase                  // FOO BAR BAZ
a.toVector                     // Vector(f, o, o,  , b, a, r,  , b, a, z)
a.trim                         // "foo bar baz"
a.view                         // 
a.zip(0 to 10)                 // Vector((f,10), (o,11), (o,12), ( ,13), (b,14), (a,15), (r,16), ( ,17), (b,18), (a,19), (z,20))
a.zipWithIndex                 // Vector((f,0), (o,1), (o,2), ( ,3), (b,4), (a,5), (r,6), ( ,7), (b,8), (a,9), (z,10))

I know I still have a few String examples to complete, but I hope the ones that I have demonstrated are helpful.

Back to top

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.