Start learning free

LESSON 278 OF 677 · STRINGS

Strings in Kotlin

Lesson

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

Creation:

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

val greeting = "Hello"

Accessing characters:

To access the characters in a string, you use square brackets with the index, like str[0].

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 the length property.

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:

val name = "John"
val 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"
val 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:

val str = "JavaScript"
val 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:

val str = "JavaScript"
val substr = str.substring(4)

println(substr) // "Script"

String Immutability:

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

For example, the following code:

val myStr = "Bob"
myStr[0] = 'J' // compile error: no 'set' operator method providing array access

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 then 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 in 0 until myStr.length) {
    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 string we iterate on.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 7
    Ctrl + Enter to check