Scala String: Creating String, Concatenation, String Length
Keeping you updated with latest technology trends, Join DataFlair on Telegram
1. Scala String – Objective
In this chapter, we will discuss Scala String in Detail. After this, you will be able to create a string in Scala. Moreover, we will learn how to create a format string and concatenate strings in Scala.
So, let’s start the Scala String Tutorial.
2. Introduction to Strings in Scala
An immutable object, a string in Scala is a sequence of characters. Once we declare it, we cannot modify it. The following is a Scala string:
3. Creating a Scala String
To define a string, we can use a ‘var’ or a ‘val’. When we use ‘var’, we can reassign to it. This isn’t the same with ‘val’:
scala> var word="rest" word: String = rest scala> word="reset" word: String = reset
By the way, reassigning ‘word’ to an Int will cause an error:
scala> word=7 <console>:12: error: type mismatch; found : Int(7) required: String word=7 ^
Now with ‘val’:
scala> val word="rest" word: String = rest scala> word="reset" <console>:12: error: reassignment to val word="reset"
We can also mention the data type if we don’t want to rely on type inference.
scala> var word:String="rest" word: String = rest scala> word="reset" word: String = reset
To make a lot of changes in your Scala string, you can use the StringBuilder class instead.
4. Find Length of a Scala String
An accessor method is one that’ll tell us about an object. One such method for strings is length(). It returns the number of characters a string holds. In the previous example,
scala> word.length() res0: Int = 5
Here are more than a couple more examples:
scala> "Ayushi".length() res1: Int = 6 scala> "".length() res2: Int = 0 scala> " ".length() res3: Int = 1
5. Concatenating Scala Strings
Concatenating two strings in Scala means joining the second to the end of the first. For this, we have the method concat() in the String class:
scala> "ab".concat("cde") res5: String = abcde
Let’s try using more than one:
scala> "Ayushi".concat(" ".concat("Sharma")) res6: String = Ayushi Sharma
We could also have done this using the + operator:
scala> "Ayushi"+" "+"Sharma" res7: String = Ayushi Sharma
6. Creating Format Strings in Scala
For the times we want to format numbers/values into our string, we can make use of one of the methods printf() and format(). Other than this, the class String has the method format() to return a String object instead of a PrintStream object.
scala> var (a:Int,b:Int,c:Int)=(7,8,9) a: Int = 7 b: Int = 8 c: Int = 9 scala> printf("a=%d, b=%d, c=%d",a,b,c)
a=7, b=8, c=9
For Integer data, we used %d. For Float and String data, we use %f and %s, respectively.
Hence, we studied how to create Scala String and creating format string in Scala. Along with this, we learned to concatenate and find a length of string. Still, have a confusion, feel free to ask in the comment session.