Updated July 3, 2023
Introduction to Scala String
Scala String class is also immutable in nature, which means that once created, cannot be changed. String is nothing but a sequence of characters or a group of characters. Strings are like constants. Once we create them, then cannot be changed. But we can make our string mutual also, but we need to use String Builder, which is also the same as java.
How to Define a String in Scala?
In Scala, we can create a string in two ways using string literal and b defining string.
varmyStr: String = "your value"
In this example, we create a string object by assigning a String keyword before the literal.
varmyStr = "your value"
In this syntax, we use a string literal to create a string object. Both the ways are the same as java with some little modification.
How to Initialize String in Scala?
We have to initialize the string at the time of declaring it.
Code:
object Main extends App{
// Your code here!
varmyStr : String = "hello."
println("Initializing the string using String keyword " + myStr)
}
object Main extends App{
// Your code here!
varmyStr = "hello."
println("Initializing the string using String literal " + myStr)
}
In these two ways, we can initialize the String in Scala.
In Scala, we have string interpolation by which we can create a String object in Scala.
This String interpolation can be achieved in three ways which are as follows:
1. ‘f’ interpolator: This ‘f’ interpolate allows us to format the string as we did in the C programming language.
Let’s take one example to format the string, and we try to attach float with a string value.
println(f"$student%s is $weight%2.2f heavy")
2. ’s’interpolator: By using this interpolator we can directly process our variable with the string itself. We just need to append them by using’s’ at the string. We just need to process the string variable that we want to show with ($variable).
println(s"start ($variablename)")
3. ‘raw’ interpolate: This interpolate will not perform any escaping of literal within the string. Apars from this, it works the same as ‘s’ interpolate.
Methods of Scala String
Given below are the in-build methods available in Scala:
- String concat(String str): This concatenates the string at the end of the current string.
- intcompareTo(Object o): This method compares one string object with another object.
- char charAt(int index): This method will return the character present at the mentioned index.
- intlength(): Return the length of the string.
- booleanmatches(String regex): Match the string with the regex.
- String replaceAll(String regex, String replacement ): Replace the string with regex matching.
- inthashCode(): Provide hashcode.
- intcompareToIgnoreCase(String str): This method is case insensitive.
- intcompareTo(String anotherString): This method compares the content of the string.
- String replace(char oldChar, char newChar): Replace the string with a new one.
- booleanequalsIgnoreCase(String anotherString): This method is case insensitive.
- String[] split(String regex): Split the string with the parameter provided.
- String substring(intbeginIndex): Return the new substring.
- String toLowerCase(): Convert the strung to lowercase.
- String trim(): Remove the space.
- String toString(): This object (which is already a string!) is itself returned.
- String toUpperCase(): Convert it to upper case.
- char[] toCharArray(): This method converts the string into the character array.
- intlastIndexOf(intch): This method returns the index of the last occurrence of the character into the string.
- byte getBytes(): This method returns the byte of the array.
- String intern(): This method returns the canonical representation.
- booleancontentEquals(StringBuffersb): This method takes the string buffer object. It will return true if the sequence matches with the string buffer.
- String[] split(String regex, int limit): This method splits the string based on the regular expression and limit.
Examples of Scala String
Given below are the examples mentioned:
Example #1
Defining and declaring a string.
Code:
object Main extends App{
// Your code here!
varmystr = "Hello, Scala!"
var mystr1 : String = "by string";
println("with string literal :: " + mystr)
println("with string keyword :: " + mystr1)
}
Output:
Example #2
This method will return the length of the string.
Code:
object Main extends App{
// Your code here!
varmystr = "check string length.."
var length = mystr.length
println("length is " + length)
}
Output:
Example #3
This method will return the String in uppercase.
Code:
object Main extends App{
// Your code here!
varmystr = "hello world...!!"
println("before upper case is " + mystr)
var upper = mystr.toUpperCase
println("After upper case is " + upper)
}
Output:
Example #4
Converting string to lowercase letter.
Code:
object Main extends App{
// Your code here!
varmystr = "HELLO WORLD BYEBYEBEY...!!"
println("before lower case is " + mystr)
var lower = mystr.toLowerCase
println("After lower case is " + lower)
}
Output:
Example#5
Performing trim in the String.
Code:
object Main extends App{
// Your code here!
varmystr = " HELLO WORLD BYEBYEBEY...!! "
println("before lower case is " + mystr)
var trim = mystr.trim
println("After lower case is " + trim)
}
Output:
Example #6
In this method, we are replacing our substring with a new one.
Code:
object Main extends App{
// Your code here!
varmystr = " HELLO WORLD BYEBYEBEY...!! "
println("before lower case is " + mystr)
var trim = mystr.replace("HELLO ", "good replcae string")
println("After lower case is " + trim)
}
Output:
Example #7
In this method, we compare to a string it will return an integer if the string matches.
Code:
object Main extends App{
// Your code here! For compare to
varmystr = "One string"
var mystr1 = "One string match"
if(mystr.compareTo(mystr1) == 0){
println("string matches!!!")
}else{
println("string does not matches !!!")
}
}
Output:
Conclusion
In Scala, String class is also immutable like Java. That means once the object is created cannot be changed. Also, we can create by using string literal and string before string literal. Also, we use string builder to make the string mutable in Scala language. But we need to make this explicit.
Recommended Articles
We hope that this EDUCBA information on “Scala String” was beneficial to you. You can view EDUCBA’s recommended articles for more information.