Start learning free

LESSON 54 OF 348 · STRINGS I

Escaping Characters in Kotlin Strings

Lesson Read the full explanation

There are times when we want to use quotes inside a string. For example, suppose we want to print the message I am John "the coder" Doe:

println("I am John "the coder" Doe")

You can already see by the text color that we have a problem. Kotlin recognizes the string to be only I am John .

Kotlin finds the first quotation mark and interprets that the string starts there. But then, it finds the second quotation mark (after John ) and interprets the string ends there.

Character escaping comes to our rescue!


Escaping characters:

In Kotlin, some characters serve different functions and so cannot be displayed or printed like other characters. These characters are referred to as special characters.

For example, double quotes (") is considered a special character by Kotlin. Its job is to let Kotlin know when a string declaration starts / ends.

There is a way to print special characters like these in Kotlin, and that is by using the backslash character (\).

When we put \ before a special character, we tell Kotlin:

"Hey, I know this is a special character, but I don't want to use it like that here. I just want to print it like I print any other character."

For example, when putting a \ before a double quote, Kotlin no longer interprets that as being the end of the string:

println("I am John \"the coder\" Doe")

println("After \"Coding 101\" we'll solve some problems")

The output of this code is:

I am John "the coder" Doe
After "Coding 101" we'll solve some problems

Escaping backslash:

Sometimes we might want to print strings that contain character \, such as a file path in your PC:

println("C:\Users\Andy\Games")

This code looks perfectly fine at first sight, but if you run it, it would produce an error: illegal escape character.

When Kotlin sees \U, it supposes that you are trying to escape character U, which is not a special character thus cannot be escaped.

Now that you've learned about its function, what type of character do you think \ is in Kotlin? It's a special character!

And like any special character, it can also be escaped by putting another \ in front of it (\\):

println("C:\\Users\\Andy\\Games")

The output of this code is:

C:\Users\Andy\Games

New line character:

Similarly, the escape sequence can be used to make an otherwise printable character serve a special function.

For example, the letter n can be printed normally, but adding a backslash before it (\n) will indicate the start of a new line:

println("Hello world!\nWhat a good day for coding!\n")
println("Let's have a blast!")

The output of this code is:

Hello world!
What a good day for coding!

Let's have a blast!

Notice the empty line after What a good day for coding! ?

That's one new line from the \n plus the new line that println() prints no matter what the message is.


Assignment
Follow the Coding Tutorial and let's escape some characters!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check

    KOTLIN · STRINGS I

    Escaping Characters in Kotlin, explained

    Why escaping exists

    A Kotlin string literal starts and ends with a double quote. That makes the double quote a special character: inside a string, it means "the string stops here". So this line can't print a quoted phrase:

    println("I am John "the coder" Doe")
    

    The compiler reads "I am John " as a complete string, then sees the coder as code, and reports errors. The string was never meant to end there.

    Escaping solves this. A backslash \ in front of a character tells Kotlin to treat that character in a special way. For a double quote, it means "this is an ordinary character, not the end of the string":

    println("I am John \"the coder\" Doe")
    println("After \"Coding 101\" we'll solve some problems")
    

    This prints:

    I am John "the coder" Doe
    After "Coding 101" we'll solve some problems
    

    The apostrophe in we'll needs no escape, because a single quote doesn't end a double-quoted string.

    The backslash itself

    The backslash is special too, since it starts every escape sequence. A Windows path such as C:\Users\Andy\Games contains backslashes that Kotlin would read as the start of escapes: \U, \A and \G. Kotlin has no escape sequence by those names, so the compiler reports unsupported escape sequence for each of them.

    To get one real backslash, write two:

    println("C:\\Users\\Andy\\Games")
    
    C:\Users\Andy\Games
    

    The pair \\ in the source code is a single character in the string. The string's length counts it as one.

    Escapes that do something special

    Escaping can work the other way too: a backslash can give an ordinary letter a special meaning. The most useful one is \n, which is a line break:

    println("Hello world!\nWhat a good day for coding!\n")
    println("Let's have a blast!")
    
    Hello world!
    What a good day for coding!
    
    Let's have a blast!
    

    The empty line comes from two line breaks in a row: the \n at the end of the string, and the one that println always adds after its argument.

    Here are the escape sequences Kotlin supports in a regular string:

    EscapeMeaning
    \nnew line
    \ttab
    \rcarriage return
    \bbackspace
    \"double quote
    \'single quote
    \\backslash
    \$dollar sign
    \uXXXXa Unicode character, given by four hexadecimal digits

    Kotlin has no other escape sequences. The dollar sign is on the list because it starts a string template: "$n" inserts the value of the variable n. To print a literal dollar sign before a name, write "It costs \$5", which prints It costs $5.

    Raw strings as an alternative

    For text full of backslashes, Kotlin has raw strings, wrapped in three double quotes. Escapes aren't processed inside them, so a path can be written as it is:

    println("""C:\Users\Andy""")
    
    C:\Users\Andy
    

    This lesson practises escape sequences in regular strings, so the exercise uses those.

    The exercise, step by step

    1. Quotes. Print I'll study "Coding 101" on AlgoCademy. Escape both inner double quotes as \". The apostrophe in I'll stays as it is.
    2. Two lines in one call. With a single println, print I will learn this and No matter what on separate lines. Put \n between them inside one string.
    3. The path. Print C:\Users\Andy\notion. Double each backslash so that none starts an escape sequence. With single backslashes, \U would be a compile error, and even if the other backslashes were doubled, the \n in \notion would become a line break instead of the letters.
    println("I'll study \"Coding 101\" on AlgoCademy")
    println("I will learn this\nNo matter what")
    println("C:\\Users\\Andy\\notion")
    

    The output:

    I'll study "Coding 101" on AlgoCademy
    I will learn this
    No matter what
    C:\Users\Andy\notion
    

    Common mistakes

    • Forgetting to escape an inner quote. The string ends early and the rest becomes code that doesn't compile.
    • A single backslash in a path. It either fails to compile, as with \U, or silently changes the text, as with \n or \t, which turn into a line break or a tab.
    • Using a forward slash for a backslash. /n is just two characters. The escape needs a backslash.
    • Putting a space after the backslash. \ n is not an escape sequence.
    • Adding \n to a println and expecting no extra blank line. println already ends its output with a line break.

    Key takeaways

    • A backslash starts an escape sequence inside a string.
    • \" prints a double quote, \\ prints a backslash and \n starts a new line.
    • A backslash before a character that Kotlin doesn't recognise is a compile error.
    • Raw strings with three double quotes skip escape processing.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free