Start learning free

LESSON 170 OF 348 · STRINGS

Strings in Scala in Scala

Lesson

The Scala String is an object that represents a sequence of characters, each identified by one index.

Creation:

To create strings in Scala, you use double quotes like this:

var greeting = "Hello"

Accessing characters:

To access the characters in a string, you can use the index in parentheses.

The following example returns the first character of a string with the index zero:

val str = "Hello"
val ch = str(0) 
// ch is "H"

Getting the length:

We can get the length of a string using length.

For example, to access the last character of the string, you use the length - 1 index:

val str = "Hello"
val ch = str(str.length - 1) 
// ch is "o"

Concatenating strings via + operator:

To concatenate two or more strings, you use the + operator:

var name = "John"
var str = "Hello " + name

println(str) // prints "Hello John"

If you want to assemble a string piece by piece, you can use the += operator:

var greet = "Welcome"
var name = "John"
greet += " to AlgoCademy, "
greet += name

println(greet) // "Welcome to AlgoCademy, John"

When concatenating many strings, it is recommended to use StringBuilder for performance

String slicing

We often want to get a substring of a string. For this, we use the substring() method.

substring(startIndex, endIndex) returns the substring from startIndex to endIndex:

var str = "Scala"
var substr = str.substring(2, 6)

println(substr) // prints "vaSc"

The startIndex is a zero-based index at which the substring() start extraction.

The endIndex is also zero-based index before which the substring() ends the extraction. The substr will not include the character at the endIndex index.

If you omit the endIndex, the substring() extracts to the end of the string:

var str = "Scala"
var substr = str.substring(4)

println(substr) // "Script"

String Immutability:

In Scala, String values are immutable, which means that they cannot be altered once created.

For example, the following code:

var myStr = "Bob"
myStr(0) = 'J' // compile error!!!

cannot change the value of myStr to "Job", because the contents of myStr cannot be altered.

Note that this does not mean that myStr cannot be changed, just that the individual characters of a string literal cannot be changed. The only way to change myStr would be to assign it with a new string, like this:

var myStr = "Bob"
myStr = "Job"
//or
myStr = "J" + myStr.substring(1, 3)

Immutability affects performance when concatenating many strings, it is recommended to use StringBuilder for performance

Convert a string to an array of characters:

When we have to change characters often in a string, we want a way of doing this quickly. Because strings are immutable, we change a character by creating a whole new string, which is O(n).

But arrays are mutable and changing an element in an array is O(1). So what we can do is first convert our string to an array of characters, operate on that array and than convert the array back to a string.

We can convert a string to an array using the toCharArray() method like this:

var str = "Andy"
val myArr = str.toCharArray()

// myArr is ['A', 'n', 'd', 'y']
myArr(0) = 'a'
myArr(2) = 'D'

// We convert an array of chars back to a string using the constructor:
str = String(myArr)

println(str) // "anDy"

Iterating through the characters:

We can iterate throught the elements of a string using indices and a for loop like this:

val myStr = "Andy"
for (i <- myStr.indices) {
    println(myStr(i))
}

// This will print the characters 'A', 'n', 'd' and 'y' on different lines

This takes O(n) time, where n is the length of the array we iterate on.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 7
    Ctrl + Enter to check

    Strings in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free