Introduction to Strings in Scala
A string is an arrangement of characters. In Scala, objects of String are permanent which implies a consistent and can't be changed once made.
Strings in Scala are fundamental data types used to represent sequences of characters. Scala's String
class is immutable, meaning that once a string is created, its value cannot be changed. This immutability ensures thread safety and simplifies concurrency management in multi-threaded applications.
Scala provides powerful string manipulation capabilities through a rich set of methods available on the String
class. Developers can concatenate strings using the +
operator or concat
method, extract substrings using substring
, and perform various transformations using methods like toUpperCase
, toLowerCase
, trim
, and more.
Use case1:
Creating a Scala String
scala> var word="Prwatech"
var word: String = Prwatech
scala> val word="Prwatech"
val word: String = Prwatech
Use case 2:
Find Length of a Scala String
scala> "Prwatech".length()
val res3: Int = 8
scala> "".length()
val res4: Int = 0
scala> " ".length()
val res5: Int = 1
Use case 3:
Concatenating Scala Strings
scala> "prwa".concat("tech")
val res6: String = prwatech
scala> "Mark".concat(" ".concat("Zuckerberg"))
val res7: String = Mark Zuckerberg
scala> "Mark"+" "+"Zuckerberg"
val res8: String = Mark Zuckerberg
Use case 4:
Creating Format Strings in Scala
scala> var (a:Int,b:Int,c:Int)=(11,12,13)
var a: Int = 11
2var b: Int = 12
var c: Int = 13
scala> printf("a=%d, b=%d, c=%d",a,b,c)
a=11, b=12, c=13
Introduction to Strings in Scala