/ KOTLINENGINEERING
5 min read

Getting In-Depth With Kotlin Strings

Introduction

A string is a basic data type in a programming language. Strings are represented by the type String. Strings are immutable. Kotlin Strings are more or less similar to Java Strings, however Kotlin has more APIs for working with strings.

This article will cover:

String Basic Usage

Declaration
// Explicit type declaration
var firstName : String = "Elon"

// or Implicit type declaration and will still compile
val lastName = "Musk"

In addition, notice the usage of val variable type, here is how it behaves

firstName = "Mark" // can be changed
lastName = "Zuckerberg" // cannot be changed
lastName = 12 // Error: type mismatch

val keyword indicates that the variable is read-only. Read Kotlin Variables.

Kotlin has a null-safety type system, before you even compile your application, it is already giving out indications of possible nullable values.

For a String, here is how it can be done

var firstName: String? = "Joshua"
var lastName: String = "de Guzman"

firstName = null // will compile
lastName = null // will not compile

Notice the firstName’s type? It has an explicit type of String?, therefore it indicates that the variable is optional and can either contain a String object or a null value. Read Kotlin Nullability.

String Concatenation

Shown in the code snippet, just like Java, appending Int to String will result to a String output

// Declaration
var str = "abc" + 1
println(str + "def")

// Output
$ abc1def

Even without explicitly converting Int value 1 to String object first, the resulting output is still a String.

In Kotlin, you can also concatenate using StringBuilder

// Declaration
val a = "Hello"
val b = "World"

val sb = StringBuilder()
sb.append(a).append(b)
val str = sb.toString()

println(str)

// Output
$ HelloWorld

You can also use Kotlin String Templates, which will be futher discussed below

// Declaration
val a = "Hello"
val b = "World"
val str = "$a $b"

println(str)

// Output
$ Hello World
String with Multiple Lines

Programmers can declare String variables with multiple lines by using triple quotes instead of double quotes

// Declaration
var str = """
        This is line 1
        This is line 2
        This is line 3
        """
println(str)

// Output
$        This is line 1
$        This is line 2
$        This is line 3

or with .trimIndent()

The use of trimIndent() will additionally help to provide a clean output format by removing excess and unnecessary indentions on each line. Examine the code snippet below:

// Declaration
var str = """
        This is line 1
        This is line 2
        This is line 3
        """.trimIndent()
println(str)

// Output
$ This is line 1
$ This is line 2
$ This is line 3

Accessing Characters of a String

Index Access

Programmers can access elements (characters) of a string using index access operator:

// Declaration
var str = "Example"
println(str[0]) // first character of the string
println(str[str.length-1]) // last character of the string

// Output
$ E
$ e

You can also retrieve characters using extension functions

// Declaration
var str = "Example"
println(str.first()) // retrieves the first character in a string
println(str.last()) // retrieves the last character in a string

// Output
$ E 
$ e

It’s just like accessing an element from an array, in Kotlin Strings you can also have some IndexOutOfBoundsException when character being accessed is out of range

// Declaration
var str = "Example"
println(str[9]) 

// Output
// Error: index out of bounds

You can also use String.get() in Kotlin, which is equivalent to Java’s String.chartAt()

// Declaration
var str = "Example"
var char = str.get(6)
println(char)

// Output
$ e
Iterate through a String

Elements of a String are characters that can be accessed by the indexing operation: s[i]

// Declaration
var str = "Example"
for (c in str) {
    println(c)
}

// Output
$ E
$ x
$ a
$ m
$ p
$ l
$ e

Kotlin also allows you to use iterator’s extension functions to a String, for example forEach

// Declaration
var str = "Hello"
str.forEach { c ->
    println(c)
}

// Output
$ H
$ e
$ l
$ l
$ o

Immutability of a String

Just like Java, you cannot change individual elements of a String

// Declaration
var str = "Example"
str[2] = "b" // Error

However you can use some operations such as replace(), if you wish to replace a specific character from a String

// Declaration
var str = "Example"
str = str.replace("m", "p")
println(str)

// Output
$ Exapple
Re-assigning String values
// Declaration
var str = "Example"
println(str)
str = "Example was changed"
println(str)

// Output
$ Example
$ Example was changed

String Properties

Determining length of a String

length returns the length of a character sequence

// Declaration
var str = "Example"
println(str.length)
println(str.length - 5) // with length() function returning Int, you can do arithmetic operations just like any other Integer value

// Output
$ 7
$ 2

String Functions

These are some of the common String functions available from the current Kotlin version

compareTo

Compares this object with the specified object for order. Returns zero if this object is equal to the specified other object, a negative number if it’s less than other, or a positive number if it’s greater than other

// Declaration
var str = "Example"
var str2 = "Example123"
var str3 = "Example12345"
println(str.compareTo(str2)) // str has fewer (3) characters than str2
println(str.compareTo(str3)) // str has fewer (5) characters than str3
println(str3.compareTo(str)) // str3 has more (5) characters than str
println(str.compareTo("Example")) // zero denotes that the String objects being compared are equal

// Output
$ -3
$ -5
$ 5
$ 0
equals

Indicates whether a String object is exactly equal to another String object

// Declaration
var str = "Example"
var str2 = "Example2"
println(str.equals("Example"))
println(str2.equals("Example"))

// Output
$ true
$ false
get

Returns the character at the specified index in this character sequence

// Declaration
var str = "Example"
println(str.get(3))

// Output
$ m
toString

Returns a string representation of the object

// Declaration
println(9.toString() + 10)
println(9 + 10)

// Output
$ "910"
$ 19

Contribution

Here is a simplified version of this article I wrote for freeCodeCamp. This is the reference to my pull request for the article submission.

For inquiries or suggestions, feel free to comment or contact me.