Scala String Methods
A string method is a built-in action that works on a string and gives back a result. Methods can change letter case, search the text, or build a new string from it.
Case methods return the text in a new case
toUpperCase turns every letter into a capital. toLowerCase turns every letter into a small letter.
@main def main(): Unit =
println("Scala".toUpperCase)
println("Scala".toLowerCase)Search methods find pieces of text
contains and startsWith answer true or false questions about the text. indexOf gives the position where the word fun starts.
@main def main(): Unit =
val text = "Scala is fun"
println(text.contains("fun"))
println(text.startsWith("Scala"))
println(text.indexOf("fun"))Cleaning methods return new strings
substring keeps the first four letters. trim removes the spaces at both ends, and replace swaps one word for another.
@main def main(): Unit =
println("Programming".substring(0, 4))
println(" hi ".trim)
println("I like Java".replace("Java", "Scala"))Example
@main def main(): Unit =
val text = "Hello Scala"
println(text.toUpperCase)
println(text.replace("Scala", "World"))
println(text.contains("Scala"))
println(text)Key points
- toUpperCase: toUpperCase returns the string with every letter in capitals.
- toLowerCase: toLowerCase returns the string with every letter in small letters.
- contains: contains reports whether a string holds a given piece of text.
- startsWith: startsWith reports whether a string begins with a given piece of text.
- indexOf: indexOf gives the position of the first match, counting from 0.
- substring: substring returns the part of a string from a start position up to an end position.
- Immutable: strings cannot be changed after creation, so trim, replace, and the other methods return new strings and leave the original as it was.
In this example, toUpperCase prints the text in capitals and replace prints it with World in place of Scala. contains prints true, and the last line prints the original text unchanged because the methods returned new strings.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Scastie
Exercise
After val word = "Scala" and println(word.toUpperCase), what does println(word) print?