Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

String

Strings in Scala are sequences of characters. Scala strings are instances of the String class in Java, which means you can use any method from the Java String class in Scala. Additionally, Scala adds its own set of methods to strings through implicit conversions to StringOps to facilitate common operations in a more Scala-like way.

Creating Strings

Creating a string in Scala is straightforward and similar to other languages:

val greeting = "Hello, World!"

String Interpolation

Scala supports string interpolation, allowing you to embed variable references directly in string literals.

  • s-Interpolator: Prepend s to the string and use $ to insert variables.
  val name = "Scala"
  val message = s"Hello, $name!"
  println(message)  // Output: Hello, Scala!

You can also use ${} to insert more complex expressions:

  val temperature = 20.5
  val weatherMessage = s"The current temperature is ${temperature}°C."
  println(weatherMessage)  // Output: The current temperature is 20.5°C.
  • f-Interpolator: Similar to s, but allows formatting.
  val height = 1.9
  val formattedMessage = f"$name%s is $height%2.2f meters tall."
  println(formattedMessage)  // Output: Scala is 1.90 meters tall.
  • raw-Interpolator: Works like s but does not escape literals.
  println(raw"New\nLine")  // Output: New\nLine

Common Operations

  • Length: Get the number of characters.
  val length = greeting.length
  • Concatenation: Combine strings using +.
  val fullGreeting = greeting + " How are you?"
  • Substrings: Extract parts of a string.
  val hello = greeting.substring(0, 5)  // "Hello"
  • Comparisons: Compare two strings, optionally ignoring case.
  val isEqual = "Scala" == "scala"  // false
  val isEqualIgnoreCase = "Scala".equalsIgnoreCase("scala")  // true
  • Searching: Check if a string contains a sequence or matches a pattern.
  val containsWorld = greeting.contains("World")  // true
  • Splitting: Split a string into an array of substrings.
  val words = greeting.split(", ")  // Array("Hello", "World!")
  • Trimming: Remove leading and trailing whitespaces.
  val spaced = "  Hello, World!  "
  val trimmed = spaced.trim  // "Hello, World!"
  • Replacing: Replace parts of the string.
  val replaced = greeting.replace("World", "Scala")  // "Hello, Scala!"
  • Case Conversion: Convert to upper or lower case.
  val upper = greeting.toUpperCase  // "HELLO, WORLD!"
  val lower = greeting.toLowerCase  // "hello, world!"

Multiline Strings

Scala supports multiline strings using triple quotes, preserving line breaks and spaces:

val multilineString =
  """This is a
    |multiline string
    |in Scala."""
    .stripMargin

The .stripMargin method removes leading spaces up to and including the character |, making it easier to format multiline strings neatly.

Exercises

Exercise 1 length

  1. Create a String "Hello, world"
  2. Print the length of the text.
  3. Split the text in words.
  4. Count the number of words.

Exercise 2 concat

  1. Create two Strings "Hello, " and "World"
  2. Concatenate the two Strings
  3. Merge the two String with s-interpolated String