Strings in Scala
In Scala, strings are sequences of characters and are represented by the String class, which is equivalent to Java’s java.lang.String.
Since Scala is interoperable with Java, you can use all the methods available in Java’s String class. Additionally, Scala provides some of its own enhancements and syntactic sugar for working with strings.
Creating Strings
You can create strings in Scala using either double quotes or triple quotes.
Single-Line String (Using Double Quotes)
val greeting: String = "Hello, Scala!"
val greeting = "Hello, Scala!" // type inference
Multi-Line String (Using Triple Quotes)
Scala allows you to define multi-line strings using triple quotes (""" ... """). This is useful for embedding long text or multi-line data without the need for escape characters.
val multiLineString: String = """This is a
multi-line
string in Scala."""
Ex:
object StringDemoA {
def main(args: Array[String]): Unit = {
var greetings = "Hello World!" // type inference - Data type String is not defined. Auto interpreted
println(greetings)
var greetingsNew:String = "Hello India!" // Data type String is defined
println(greetingsNew)
}
}
Common Operations on Strings
Length
To get the length of a string:
var greetings = "Hello World!"
// Method to get length of String (Accessor Method - Any method {Eg length()} used to get information of an object {Eg: greetings} is called Accessor Method)
var lengthOfString = greetings.length()
println("Length of String greetings : Hello World! is " + lengthOfString)
val name = "Scala"
println(name.length) // Output: 5
Concatenation
You can concatenate strings using the + operator or concat method:
// concat method
var var1 = "Hello "
var var2 = "World"
println(var1 + var2 + "!") // You can concat using + operator/method
println(var1.concat(var2)) // you can also use concat method
val firstName = "John"
val lastName = "Doe"
val fullName = firstName + " " + lastName // Output: "John Doe"
String Comparison
You can compare strings using == or .equals:
// Equals method
var varA = "Hello World!"
var varB = "Hello World!"
println(varA.equals(varB)) // Gives true, if both the Strings are having same contents
println(varA == varB) // Note: Same as equals. But does one additional step. It first checks varA and varB are not null
val str1 = "Scala"
val str2 = "Scala"
println(str1 == str2) // Output: true
println(str1.equals(str2)) // Output: true
String Interpolation
Allowed since Scala 2.10 onwards.
Scala offers string interpolation, a powerful feature for embedding expressions within strings. There are three types of string interpolators: s, f, and raw.
sInterpolator: Allows embedding variables and expressions directly within strings using${}syntax.
val name = "Scala"
val version = 3.0
println(s"Welcome to $name version $version!") // Output: "Welcome to Scala version 3.0!"
// 1. 's' String Interpolator
var name = "PM Modi"
println("Hello " + name + ", How are you?") // using + to concat
println(s"Hello $name, How are you?") // using s interpolator. Widely used
fInterpolator: Used for formatted strings, similar toprintfin other languages.
val pi = 3.14159
println(f"Pi is approximately $pi%.2f") // Output: "Pi is approximately 3.14"
// String Formatting
var nameOfCar = "Mercedes"
var costOfCar = 500000
var milageOfCar = 8.5
printf("Name of Car is %s and cost of Car is %d and milage of Car is %f", nameOfCar, costOfCar, milageOfCar)
rawInterpolator: Similar to thesinterpolator but treats escape sequences literally. It does not perform escaping.
val rawString = raw"This is a\nnew line"
println(rawString) // Output: "This is a\nnew line"
// 3. raw Interpolator - Same as s interpolator but does not perform escaping. escaping - \n \t
println(s"Hello World!\nHow are you?")
println(raw"Hello World!\nHow are you?")
Substring
To extract a part of the string (substring):
val text = "Hello, Scala!"
val substring = text.substring(7, 12) // Output: "Scala"
String Splitting
To split a string by a delimiter:
val sentence = "Scala is fun"
val words = sentence.split(" ") // Output: Array("Scala", "is", "fun")
Uppercase and Lowercase
Convert strings to uppercase or lowercase:
val lower = "scala"
val upper = lower.toUpperCase() // Output: "SCALA"
val mixedCase = "ScaLa"
val lowerCase = mixedCase.toLowerCase() // Output: "scala"
String Reversal
To reverse a string:
val word = "Scala"
val reversed = word.reverse // Output: "alacS"
Checking for a Substring
To check if a string contains another string:
val sentence = "Scala is great"
println(sentence.contains("Scala")) // Output: true
Multiline Strings
Use 3 double inverted commas “”” string “””. Also use | symbol and stripMargin function for orientation.
// using double inverted commas
var multiLineStringA =
"""Hello
World
How
are
you
"""
println(multiLineStringA)
var multiLineString =
"""Hello
|World
|How
|are
|you
""".stripMargin
println(multiLineString)
var multiLineStringB =
"""Hello
$World
$How
$are
$you
""".stripMargin('$')
println(multiLineStringB)
Summary:
- Strings in Scala are represented by the
Stringclass, inherited from Java. - Scala adds powerful features like string interpolation (
s,f,raw), multi-line strings, and syntactic sugar for common string operations. - Most common string operations (concatenation, substring, length, comparison) are available as methods of the
Stringclass.
Example :
object StringExample {
def main(args: Array[String]): Unit = {
val name = "Scala"
val version = 3.0
// String interpolation with `s`
println(s"Welcome to $name version $version!")
// String interpolation with `f`
val pi = 3.14159
println(f"Pi is approximately $pi%.2f") // Output: "Pi is approximately 3.14"
// String operations
val greeting = "Hello, Scala!"
println(greeting.length) // Output: 13
println(greeting.substring(7, 12)) // Output: "Scala"
println(greeting.toUpperCase()) // Output: "HELLO, SCALA!"
}
}