By definition, a string is a sequence of characters. Every string object in Scala
is immutable/constant. Once created, the object cannot be changed.
Like strings in other languages, Scala strings also support the use of string methods to manipulate the string. Notable methods include length()
, concat()
, substring()
, trim()
.
length()
: Calculates length of a string.
concat()
: Joins two strings into one using the +
operator.
substring()
: Extracts a portion of a string.
trim()
: Removes trailing spaces. For example, "hello ", will return “hello”, removing the extra spaces at the end.
Strings in Scala can be defined using two methods:
var str = "String by method 1"
: In this method, the compiler encounters a string literal and creates a string object.var str: String = "String by method 2"
. In this method, the type is specified before the declaration of the string literal.object Main extends App {var str1 = "Hello World"val str2: String = "Welcome to Educative"// Display both stringsprintln(str1);println(str2);// display lengthprintln(str1 + ", Length: " + str1.length());println(str2 + ", Length: " + str2.length());// concat operationvar new_str: String = str1.concat(str2)println("concatenated string: " + new_str)// substring take three character from index 0: startvar subs: String = str1.substring(0,3)println("substring: " + subs)}
Free Resources