SCALA STRINGS IN SIMPLE WORDS

Reading Time: 6 minutes

A string is nothing but a data type used in programming to represent text rather than numbers. A string is a combination of characters and can contain letters, numbers, symbols, and spaces. Scala Strings should be enclosed in double-quotes.

For example, the word “computer” and the phrase “who invented the computer?” are both strings. A sequence of characters “abdj@nfi%*&23kh09i2^l” is also considered a string.

In this chapter, we are going to discuss Scala strings in deep like some built-in functionality of string and predefined function of Scala string.

Let’s start with Scala string in simple words, How to declare string in Scala?

// Explicitly mentioning the data type
val expStringDeclaration: String = "Scala Strings"
println(expStringDeclaration) 

// Using type inference
val infStringDeclaration = "Type Inference of Scala string!"
println(infStringDeclaration)  

If you know other programming languages then Scala strings are very similar to other programming languages like java, c and python, etc. Internally Scala’s string is built on Java’s string with added unique features.

Let’s discuss the built-in feature of Scala strings.

Length of Scala strings

To calculate the length of the string we have length function in Scala.

val stringLength = "What is the length of this string?" 

println(stringLength.length)    //Output --> 34

Concatenation on Scala strings

String concatenation means joining two or more strings into a single string and concatenation of two or more strings is done using the + operator.

println(“Hello” + “string Concatenation”)  //Concatenating without variables

Every operator in Scala we can use as a function so we can also concatenate two strings in the below way

println("Hello ".+("World!"))   //Concatenating without variables 

val string1 = "Hello "
val string2 = "World!"

print(string1.+(string2))    //Concatenating using variables

We can also concatenate other data types with strings as well, such as Int or Float.

Println(5 + " is the integer " )  //Concatenating a string with an integer

//Concatenating a string with a floating point
val aFloat = 1.5F
println("This is the floating point value " + aFloat)

Scala Strings Comparison

If you want to compare two string objects whether they are identical or not, use the == method to test the equality of two objects. The result will either be true or false depending on whether the objects are equal or not.

val string1 = "scalaString"
val string2 = "ScalaString"

val checkEquality = string1 == string2

println(checkEquality)

After execution of the above code, we will get false as output because the first character of both the strings is different i.e. string1 has lowercase s while string2 has uppercase S.

equal method

Scala string also has an equal method to compare two strings. The equal method is the same as == the only difference is we need to pass string2 in the argument.

val string1 = "scalaString"
val string2 = "ScalaString"

val checkEquality = string1.equal(string2)

println(checkEquality)

compareTo method

compareTo compares two strings lexicographically i.e., in alphabetical order, Unlike the other methods we have used above, compareTo returns an integer number, and that integer is the mathematical difference between the strings.

  • 0 is returned –> Strings are identical.
  • a positive number is returned –> string1 is greater than string2.
  • a negative number is returned –> string1 is less than string2.

Internally string1 is subtracted from string2.

val string1 = "This is Scala "
val string2 = "Hello Scala"  
val string3 = "Hello Scala" 

val lexiCompare1 = string1.compareTo(string2) //string2-string1
val lexiCompare2 = string2.compareTo(string3) //string3-string2

println(s"Comparing string1 and string2: $lexiCompare1")  
println(s"Comparing string2 and string3: $lexiCompare2") 

equalsIgnoreCase method

It is similar to the equal method with the added feature that it ignores cases. So, for equalsIgnoreCase, “s” is equivalent to “S”.

val string1 = "scalaString"
val string2 = "ScalaString"

val checkEquality = string1.equalsIgnoreCase(string2)

println(checkEquality) //true

Scala Strings character case conversion

Scala string has toUpperCase(use to convert the character of strings to upper case) and toLowerCase(use to convert the character of strings to lower case).

val string1 = "scalaString"
val string2 = "ScalaString"

var checkEquality = string1.toUpperCase == string2.toUpperCase
println(checkEquality) // true

checkEquality = string1.toLowerCase == string2.toLowerCase
println(checkEquality) // true

Splitting on Scala Strings

In scala, we can use split method to split the strings at specific separators such as spaces, commas. Internally, A split method converts a string into an array of String elements and returns that array. For example, if we have a string “Car Bus Train” and apply the split method on it with a space separator, we would get an array of type String containing three elements: “Car”, “Bus”, and “Train”.

The split method takes one argument which lets the compiler know which separator it should split the string at.

val splitCar = "BMW, Mercedes, Audi, Toyota, Ford, Maruti, Hyundai".split(",")

splitCar.foreach(println)

In the above example, we used for each to print the output because splitCar is not a simple variable, It is an array.

String Interpolation

Apart from SCALA built-in function, Scala strings have a unique and infamous feature: String interpolation

String interpolation is the ability to create new strings or modify existing ones by embedding them with expressions.

We can modify our existing string by three inbuilt interpolation methods:

s
f
raw

String interpolation with s

Prepend an s to any string literal and it will allow us to use any variable/expression inside the string with the help of $(dollar) sign.

Syntax for Variables

s”optional string $variableIdentifier optional string”

val car : “Mercedes-benz”
println(s”I want to buy $car car !”)

Syntax for Expression

s”optional string ${expression} optional string”

println(s”Sum of first 5 natural numbers is ${(5(5+1))/2}”)

String interpolation with f

f string interpolation is scala’s printf method. Prepend an f to any string literal and it will allow us to create formatted strings. When using this interpolation, all references to variables and expressions should be followed by a printf style format string, like %f.

Syntax

f”optional string $variableIdentifier%FormatSpecifier optional string”

val pi = 3.14159F

println(f"the value of pi is $pi%.3f")

In the above example, pi is our variable identifier and %.3f is the format specifier and f interpolated string is telling the compiler to print floating-point number pi up to 3 decimal places.

Scala has several format specifiers that we can use in different scenarios. First, we will look syntax of the format specifier then we will play with the format specifier.

Syntax of format specifier

%FlagWidth.PrecisionConversion-Character

  • % –> It is a keyword that must be user when we are formatting our string.

  • Flag –> Flags are general modifiers and mostly used to format integer and floating numbers. Below is the list of flags.
Flag Uses
left-justify(If we want to left justify our formatted variable then we can use it)
+ It is used to add + signature.
0 It is used to add padded zeros.
, It is used to add a local-specific grouping separator.
  • Width –> If we want to print minimum length output then we should use width. For example, if we say %5d, we mean that the output of the integer should be a minimum of 5 characters. To fulfil our requirement, the compiler will insert spaces before our argument until it is 5 characters long, pushing the argument further right.

  • Precision –> It can only be used in floating point number as we used in our first example %.3f. Mentioning the precision %.3f, we told the compiler to print upto 3 decimal places of our floating point number.

  • Conversion Character –> It is the most important part of formatting because Flag, width and precision are optional but conversion character is required. Conversion-characters do the actual formatting and determine how the argument is to be formatted. Lets see some important conversion character that we will use in our examples.

Conversion Character

Conversion Character Uses
s It is use for string formatting.
d It is used for decimal integers formatting.
f It is used for floating-point numbers formatting.
t It is used for date/time values formatting.
val decimalvalue = 15322

println(f"Without Formatting: $decimalvalue is the output")
println(f"With Width: $decimalvalue%10d is the output")
println(f"With Flag: $decimalvalue%-10d is the output")

First print statement, It will print the same value of decimalvalue identifier without any formatting.

Second print statement, It will print the formatted value of decimalvalue identifier without like It added spaces before the variable value(right justify) to complete 10 places.

Third print statement, It will print the formatted value of decimalvalue identifier without like It added spaces after the variable value(left justify) to complete 10 places.

copy the above code and run it into the compiler you will get better visibility.

String interpolation with raw

raw string interpolation is similar to s string interpolation. The only difference is that raw does not recognize character literal escape sequences.

we prepend the word raw to any string literal. This allows us to print characters’ symbols within strings.

Syntax

raw”optional string EscapeSequences optional string”

println("Without Raw:  \n First \n Second")

println(raw"With Raw : \n First \n Second")

In a first print statement, \n works as an escape character and sends the control to the next line but as we used raw string interpolation in the second print statement compiler will ignore \n as escape character and print as it is.

In this article, we learned how to define a string in Scala, important built-in functions of Scala string, and the most unique feature of Scala string that is String interpolation with examples.

References

https://docs.scala-lang.org/overviews/core/string-interpolation.html

Written by 

Nikhil Gupta is software consultant in knoldus. I am punctual, detailed oriented, multitasking and innovative. I believe that practice makes a man perfect with full commitment, planned strategies.

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading