Scala – String

Scala string is a sequence of characters inside quotes. It is an immutable object like in java that means its values can not be modified. When you write a String in REPL (Read-Evaluate-Print-Loop) environment, and get the name of the String literal, it will print java.lang.String which tells us that scala uses java String class, hence allows us to use its methods in scala.

String in Scala prints java.lang.String

As you can see in the above image, we have defined the type as String while declaring variable str. What if we do not mention the type and write the String as given below?

It will also work , as compiler understands it as String literal and creates a string object str. We can see an example how it is an immutable object. If we replace the characters in the string , it gives a new string and original string str remains intact. We are replacing “Emp” with “123” ,and it gives a new string. But String str remains as Employee when printed again.

Now, let’s see some important methods of string.

Consider that we have a string object as – val str = “Employee”.

str.length

It returns the length of the string in characters.

str.substring(i)

It returns the part of string staring at index i. Index start from 0.

str.substring(i,j)

It returns the part of String starting at index i and goes till index (j-1).

str.slice(i,j)

It also works the same as substring and gives the same result.

str.contains(x)

It returns boolean value as true if x is substring of str.

str.indexOf(x)

It returns the index of first occurrence of substring in string str or -1 if not present.

str.toLowerCase

Converts string into lower case.

str.toUpperCase

Converts string into uppercase.

str.capitalize

returns a string with first character as upper case.

str.isEmpty

returns boolean value true if string object is empty else false. It is same like str.length==0.

str.startsWith(x)

returns true if str starts with x. It is case sensitive.

str.endsWith(x)

returns true if str ends with x. It is case sensitive.

str.reverse

returns reversed string.

str.replace(x,y)

It returns a new string with all characters x replaced by y.

str.trim

It returns a string with white spaces removed both the side.

str.split(delimiter)

It splits the string on the basis of delimiter and returns a array of strings.

Scala Closure
Scala - String Interpolation
Shekhar Sharma

Shekhar Sharma

Shekhar Sharma is founder of testingpool.com. This website is his window to the world. He believes that ,"Knowledge increases by sharing but not by saving".

You may also like...

Leave a Reply

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