Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 134 ยท Getting Started

Strings

Learn Kotlin strings - immutability, escapes, raw strings with trimIndent, indexing, common functions, comparison, StringBuilder, Char and Unicode pitfalls, with runnable examples.

Almost every program handles text: names, messages, file contents, JSON, log lines. In Kotlin, text is a String, a sequence of characters written between double quotes. Kotlin's String is the same class as Java's java.lang.String, but the standard library adds dozens of friendly functions on top of it, so everyday text work reads much better than in Java.

This lesson covers what a string is, how to write one (normal and raw), how to look inside it, the functions you will use daily, how comparison works, and when to reach for StringBuilder. Interpolation with $name and number formatting get their own lesson: String Templates and Formatting.

Strings are immutable

A String never changes after it is created. Every function that looks like a modification, such as uppercase() or replace(), returns a new string and leaves the original alone. That is why you cannot assign to a character with s[0] = 'x' (the compiler rejects it), and why a plain val string is perfectly safe to share between parts of a program.

Kotlin Strings never change, functions return new ones

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last two lines of main show a subtle point. text is a var, so it can point to a different string later. text += "def" does not extend the old string in place. It builds a new string "abcdef" and makes text refer to it. The old "abc" is garbage the JVM will clean up.

Writing string literals

An ordinary literal sits on one line and uses backslash escapes for special characters:

Escape Meaning
\n new line
\t tab
\" a double quote
\\ a backslash
\$ a dollar sign (otherwise it starts a template)
\u00E9 the character with Unicode code 00E9 (here "e" with an acute accent)

Kotlin supports only a small set of escapes: \t, \b, \n, \r, \', \", \\, \$ and \uXXXX. If you write an unknown escape such as \d (a classic mistake when writing regular expressions), the compiler refuses to build the program.

A raw string is written with triple quotes. Nothing inside is escaped, and it may span several lines, which makes it perfect for file paths on Windows, regular expressions, JSON and SQL:

Kotlin Escaped strings and raw strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Two helpers matter for raw strings. trimIndent() removes the common leading whitespace from every line and drops the first and last line if they are blank, so you can indent the text to match your code without that indentation ending up in the data. trimMargin() removes everything up to and including a margin character (| by default) at the start of each line, and is handy when some lines must keep deeper indentation than others.

A raw string still supports templates: """Total: $total""" inserts the value. To write a literal dollar sign in a raw string use ${'$'}, because there is no backslash escape.

Kotlin has no separate "multi-line string" type: it is the same String, and a raw string with newlines simply contains \n characters.

Looking inside a string

A string is an ordered sequence of Char values. You read one with the index operator, counting from zero, and you can ask for its length:

Kotlin Indexing, slicing and searching

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Indexing past the end throws an exception. Run this to see the real message:

Kotlin An index outside the string (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The program stops with java.lang.StringIndexOutOfBoundsException, and the message says the index 10 is out of bounds for length 6. When you are not sure an index exists, use getOrNull(10), which returns null instead of throwing (see Null Safety), or check with in s.indices.

A close relative of substring is subSequence(start, end). It comes from the CharSequence interface and has the same exclusive end index. On a String it returns the same text as substring, but its declared type is CharSequence, so call toString() when you need a real String type again:

Kotlin subSequence

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The output is Kotlin, 6 and KOTLIN. Prefer substring for plain strings; subSequence matters when your function accepts any CharSequence, such as a StringBuilder.

substring(start, end) uses an exclusive end, like most ranges in Kotlin. You can also slice with a range: s.substring(0..4) or the shortcut s.slice(0..4).

Everyday functions

The standard library has a function for nearly every small text chore. These are the ones you will use all the time:

Kotlin The text functions you will use daily

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A few notes that save time:

  • isEmpty() is true only for length zero. isBlank() is also true for strings that contain only spaces, tabs and newlines. For user input you nearly always want isBlank().
  • uppercase() and lowercase() replaced the old toUpperCase() and toLowerCase(), which are deprecated. For the same reason capitalize() is gone; write replaceFirstChar { it.uppercase() }.
  • split returns a List<String>. If you pass a String delimiter it is taken literally; to split with a pattern use a Regex (see Regular Expressions).
  • padStart and padEnd pad to a total width. They never shorten a string.

Comparing strings

In Kotlin the == operator compares content, not identity. This is different from Java, where == on strings compares references and surprises every beginner. In Kotlin, == calls equals(), so you can write the natural thing:

Kotlin Equality and ordering of strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

=== checks whether two references point at the very same object, and you almost never want it for strings. The comparison operators < and > use compareTo, which orders strings by the numeric code of their characters. That is why every uppercase letter sorts before every lowercase one. To sort in a human way, compare lowercase copies or use a Collator, and see Sorting and Comparators.

StringBuilder: building text in a loop

Because strings are immutable, result += piece inside a loop copies the whole string on every pass. For a handful of pieces that is fine. For thousands, the total work grows with the square of the final length. A StringBuilder holds a growable buffer and appends in place:

Kotlin Concatenation in a loop versus StringBuilder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

buildString { ... } creates a StringBuilder, runs your block with it as this, and returns the finished String. It is the idiomatic choice. When you are just joining items with a separator, joinToString is shorter still. You will see StringBuilder directly when you need insert, reverse or setCharAt.

Characters and Unicode

Each element of a string is a Char, written with single quotes: 'a'. A Char is a 16-bit UTF-16 code unit, not necessarily a whole visible character. Most text fits one unit per character, but emoji and some rare scripts need two units (a surrogate pair), so length counts units, not what a reader sees:

Kotlin Chars, code points and emoji

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

digitToInt() is the safe way to turn '7' into 7; '7'.code would give 55, the numeric code of the character. For everyday English text you can ignore surrogate pairs. When you process names, chat messages or anything emoji-friendly, count with codePointCount and do not cut a string between the two halves of a pair.

Use String functions that take a Char when you can (indexOf('x'), split(',')). They are a little faster and read more clearly than one-letter strings.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does val t = s.uppercase() do to the string s?

    Strings are immutable. Functions like uppercase() return a new String; the original keeps its content.
  2. 2. What does == do when comparing two String values in Kotlin?

    == is structural equality and calls equals(). Use === only for reference identity, which you rarely need for strings.
  3. 3. Which literal is best for a Windows path like C:\Users\kim without doubling backslashes?

    A raw string """C:\Users\kim""" has no escapes, so backslashes mean themselves.
  4. 4. Why is a StringBuilder (or buildString) better than += inside a long loop?

    Each += on a String creates a new string and copies the old content. A builder appends into a growable buffer and converts once at the end.
  5. 5. What is "I \uD83D\uDE00 Kotlin".length compared to the number of visible characters?

    length counts UTF-16 units. The emoji is a surrogate pair of two units, so length is one more than the number of visible characters.

Summary

  • A String is an immutable sequence of Char values; functions return new strings.
  • Use "..." with escapes for short text and """...""" raw strings for paths, regexes and multi-line text, tidied with trimIndent() or trimMargin().
  • Read characters with s[i] (zero-based), slice with substring, take, drop, and search with indexOf and in.
  • == compares content, === compares identity, and < orders strings by character code.
  • Use isBlank() for user input, uppercase()/lowercase() instead of the deprecated names, and buildString or joinToString instead of repeated += in loops.
  • length counts UTF-16 units, so emoji count as two.

Next: String Templates and Formatting