🎓 A1Learner
🔍
0 of 50 lessons completed

Scala String Operations

String operations are actions that join, measure, compare, and pick characters from text. Scala strings support all four actions with short built-in tools.

The + sign joins strings together

The + sign joins the two pieces into one string. The joined result prints as one line.

@main def main(): Unit =
  val greeting = "Hello, " + "Scala"
  println(greeting)

length counts the characters in a string

The short word has five letters. The longer word has eleven letters.

@main def main(): Unit =
  println("Scala".length)
  println("Programming".length)

Equality compares content and charAt picks a character

Equal text gives true and different text gives false. Position 1 in Scala is the second letter, c.

@main def main(): Unit =
  println("cat" == "cat")
  println("cat" == "dog")
  println("Scala".charAt(1))

Example

@main def main(): Unit =
  val first = "Ana"
  val last = "Lee"
  val full = first + " " + last
  println(full)
  println(full.length)
  println(full.charAt(0))
  println(first == "Ana")

Key points

  • Concatenation: the + sign joins two strings into one longer string.
  • length: length counts the characters in a string, including spaces.
  • Equality: == checks whether two strings hold the same characters.
  • Content: == compares the text inside the strings, not where the strings are stored.
  • charAt: charAt picks the character at a numbered position, and counting starts at 0.

In this example, first and last are joined with a space to make the full name Ana Lee. The program prints its length 7, its first character A, and true because first holds the same text as Ana.

Note

in Scala, == on strings compares content, which differs from some other languages.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does "Scala".charAt(0) give?