Scala String Basics

Strings are sequences of characters. In Scala, a String is backed by Java's java.lang.String, which means every Java String method is available alongside Scala's own additions. Strings are immutable — every operation that appears to modify a string actually creates a new one.

Creating Strings

val name = "Scala"                    // double quotes
val sentence = "Learning is fun"
val empty = ""                        // empty string
val withQuote = "She said \"hello\""  // escaped quotes
val multiLine = "Line one\nLine two"  // \n is a newline

Escape Sequences


Sequence   Meaning
────────   ─────────────────
\n         New line
\t         Tab character
\\         Backslash
\"         Double quote
\r         Carriage return
\b         Backspace
println("Column1\tColumn2\tColumn3")
// Column1   Column2   Column3

println("First line\nSecond line")
// First line
// Second line

Raw Strings (Triple Quotes)

Triple-quoted strings preserve whitespace and newlines exactly as written, and do not process escape sequences:

val address = """123 Main Street
Mumbai, MH 400001
India"""
println(address)
// 123 Main Street
// Mumbai, MH 400001
// India

val regex = """(\d{3})-(\d{4})"""   // no need to escape backslashes

Use triple-quoted strings for multi-line text, JSON templates, SQL queries, or regex patterns where backslash escaping would clutter the code.

String Length and Access

val word = "Elephant"

println(word.length)      // 8
println(word.size)        // 8 (same as length)
println(word.charAt(0))   // E
println(word(0))          // E (shorthand for charAt)
println(word.charAt(7))   // t
println(word.head)        // E (first character)
println(word.last)        // t (last character)

Index:  0   1   2   3   4   5   6   7
Char:   E   l   e   p   h   a   n   t

Substrings

val language = "Functional Scala"

language.substring(11)       // "Scala"
language.substring(0, 10)    // "Functional"
language.take(10)            // "Functional"
language.drop(11)            // "Scala"
language.slice(0, 4)         // "Func"

Searching in Strings

val text = "Scala is a scalable language"

text.contains("scala")          // false (case-sensitive)
text.contains("Scala")          // true
text.indexOf("scala")           // 10 (lowercase "scala")
text.indexOf("xyz")             // -1 (not found)
text.startsWith("Scala")        // true
text.endsWith("language")       // true
text.matches(".*scalable.*")    // true (regex match)

Case Conversion

val mixed = "Hello, World!"

mixed.toUpperCase   // "HELLO, WORLD!"
mixed.toLowerCase   // "hello, world!"
mixed.capitalize    // "Hello, World!" (first char uppercase)
"hello world".capitalize  // "Hello world"

Trimming Whitespace

val padded = "  hello world  "

padded.trim         // "hello world"
padded.strip        // "hello world" (Unicode-aware)
padded.stripLeading // "hello world  "
padded.stripTrailing // "  hello world"

Splitting and Joining

val csv = "Alice,30,Mumbai"
val parts = csv.split(",")
// Array("Alice", "30", "Mumbai")

println(parts(0))   // Alice
println(parts(1))   // 30

// Join an array back into a string
val rejoined = parts.mkString(" | ")
println(rejoined)   // Alice | 30 | Mumbai

// Split on whitespace
val sentence = "the quick brown fox"
val words = sentence.split(" ")
println(words.length)   // 4

Replace and Substitution

val original = "I love Java and Java is great"

original.replace("Java", "Scala")
// "I love Scala and Scala is great"

original.replaceFirst("Java", "Scala")
// "I love Scala and Java is great"

"hello123world".replaceAll("[0-9]", "#")
// "hello###world"

Checking String Content

val num = "12345"
val text = "hello"
val blank = "   "

num.forall(_.isDigit)     // true  — all digits
text.forall(_.isLetter)   // true  — all letters
blank.isBlank             // true  — only whitespace
"".isEmpty                // true  — empty string
"a".nonEmpty              // true  — not empty

Converting Strings to Other Types

"42".toInt        // 42
"3.14".toDouble   // 3.14
"true".toBoolean  // true
"99".toLong       // 99L

// Safe conversion with Try
import scala.util.Try
Try("abc".toInt).toOption   // None (won't crash)
Try("42".toInt).toOption    // Some(42)

String Comparison

val s1 = "apple"
val s2 = "banana"
val s3 = "Apple"

s1 == s2                        // false
s1 == "apple"                   // true
s1.equalsIgnoreCase(s3)         // true (case-insensitive)
s1.compareTo(s2)                // negative (a < b)
s1.compareToIgnoreCase(s3)      // 0 (equal ignoring case)

Useful String Methods Summary


Method                  What it does
──────────────────────  ────────────────────────────────
length / size           Number of characters
charAt(i) / apply(i)    Character at index i
substring(start, end)   Extract a portion
contains(sub)           Check if substring exists
indexOf(sub)            Position of first match (-1 if not found)
startsWith(prefix)      Check beginning
endsWith(suffix)        Check ending
toUpperCase             All caps
toLowerCase             All lowercase
trim / strip            Remove leading/trailing whitespace
replace(old, new)       Substitute all occurrences
split(delimiter)        Break into array
mkString(sep)           Join with separator
toInt / toDouble        Parse to number
isEmpty / nonEmpty      Check if empty
reverse                 Reverse the characters
repeat(n)               Repeat n times (Scala 3 / Java 11+)

String as a Sequence of Characters

Scala treats a String as a sequence of characters, so all collection methods work on it:

val word = "Scala"

word.map(_.toUpper)           // "SCALA"
word.filter(_.isVowel)        // Not valid directly — use:
word.filter("aeiouAEIOU".contains(_))   // "aa"
word.foreach(println)         // S, c, a, l, a (each on new line)
word.toList                   // List('S', 'c', 'a', 'l', 'a')
word.sorted                   // "Saacl"  (alphabetical)
word.distinct                 // "Scal"   (unique characters)
word.count(_ == 'a')          // 2

This makes Scala strings much more powerful than strings in many other languages — every list operation applies to string characters without any conversion overhead.

Leave a Comment

Your email address will not be published. Required fields are marked *