CodeGym /Courses /Kotlin SELF /Strings and text: the String type, working with strings

Strings and text: the String type, working with strings

Kotlin SELF
Level 2, Lesson 2
Available

1. Taking a closer look at the String type

The String type is one of the most frequently used types in Kotlin. Possibly the most used one. It is a great type, because you can store text in such variables. Also, unlike Int and Double, objects of type String have a bunch of different functions, and with those functions you can do various interesting things.

In addition, all objects in Kotlin (literally all of them) can be converted to the String type. Or, more correctly, all objects in Kotlin return their textual (string) representation. We will come back to this type more than once (it is very useful and interesting), but today we will get familiar with its basics.

Creating variables of type String

The String type is designed to store strings (text). To create a variable in code that can store text, you need to use the command:

var name: String
Creating a variable of type String

Where name is the variable name.

Examples:

Command Description
var name: String
A string variable name is created
var message: String
A string variable message is created
var text: String
A string variable text is created

Just like with Int and Double, you can create multiple variables of type String.

In Kotlin, comma-separated declarations like in Java (String a, b;) are not used — variables are declared separately:

fun main() {
    var name1: String
    var name2: String
    var name3: String
}

2. Assigning values to variables of type String

To put a value into a variable of type String, you need to use the command:

name = "value"
Assigning a value to a variable of type String

And here is the first difference from the types you have already studied. All values of type String are text strings and must be enclosed in double quotes.

Examples:

Command Note
var name: String = "Anya"
The variable name contains the text Anya
var city: String = "New York"
The variable city contains the text New York
var message: String = "Hello!"
The variable message contains the text Hello!

3. Initializing variables of type String

As with Int and Double, variables of type String can be initialized right when they are created. By the way, you can do this with any type in Kotlin. So we will not talk about it anymore.

fun main() {
    var name1: String = "value1"
    var name2: String = "value2"
    var name3: String = "value3"
}
General form of creating and initializing variables
fun main() {
    var name: String = "Anya"
    var city: String = "New York"
    var message: String = "Hello!"
}
Example of creating and initializing variables

You can change only variables that have a value

The Kotlin compiler will complain if you declare a variable without assigning any value to it and then try to use it.

This code will not work:

fun main() {
    var name: String
    println(name) // The variable name is not initialized. The program will not compile.
}
fun main() {
    var a: Int
    a++ // The variable a is not initialized. The program will not compile.
}
fun main() {
    var x: Double
    val y = x // The variable x is not initialized. The program will not compile.
}

4. Concatenation — joining strings

There is a very interesting and simple thing you can do with strings in Kotlin — you can join them together. This operation is called concatenation. It is also often called “joining strings” or even simply “adding strings”.

To join two strings, you need to use the + sign. It is very simple:

val result = "string1" + "string2"
Concatenation of two strings

Examples:

Command Note
val name = "Anya" + "Anya"
name contains the string AnyaAnya
val city = "New York" + "Anya"
city contains the string New YorkAnya
val message = "Hello! " + "Anya"
message contains the string Hello! Anya

And, of course, you can concatenate many strings at the same time, as well as concatenate strings with variables.

Examples:

fun main() {
    val name = "Anya"                  // name contains the string Anya
    val city = "New York"             // city contains the string New York
    val message = "Hello!" + city + name + city // message contains the string Hello!New YorkAnyaNew York
}

5. Empty strings

In the last example, you can see that the text in the message variable is hard to read, because it lacks spaces. To insert one space or several, you just need to write them in code and wrap them in double quotes. It is easier than it sounds:

" "
A string containing a single space

By the way, if you leave absolutely no space between the quotes (write two double quotes in a row), you get a so-called “empty string”:

""
Empty string

On the one hand, it exists, but on the other hand, when you print it to the screen, nothing is printed. And when you concatenate it with other strings, nothing happens. It is kind of like zero, but for strings.

6. Escaping special characters in strings

You already know that strings are surrounded by double quotes. But what if you need to insert quotes inside a string? If we write quotes inside the string, would the compiler treat them as the end of the string?

Correct. It will. Therefore, quotes inside text are replaced with the pair of characters \". And the code will look like this:

fun main() {
    val quote = "He said: \"Hello!\""
    println(quote) // He said: "Hello!"
}

In fact, it is a bit trickier. The \ character is considered a special (escape) character inside strings. With it, you can specify various “non-printable characters” like newline, tab, etc. And to represent the \ character itself, you need to write it twice.

Here are the 4 most common combinations:

Notation Meaning
\n
New line (newline)
\t
Tab (indent)
\\
Literally \
\"
Quotes inside a string

Example:

fun main() {
    val multiline = "Line 1\nLine 2"
    println(multiline)
}

Will print:

// Line 1
// Line 2

7. Built-in string functions

The String type has its own functions (also called methods). There are a lot of them, and they make programmers’ lives easier. Today you will get acquainted with some (the simplest) of them. Example:

Function Description Example result
str.length
String length
"abc".length → 3
str.uppercase()
To uppercase
"abc".uppercase() → "ABC"
str.lowercase()
To lowercase
"ABC".lowercase() → "abc"
str.trim()
Remove spaces at the edges
"  x y  ".trim() → "x y"

Examples of working with string functions

All these functions are called like this: variable.function(...).

Get the length of a string:

fun main() {
    val name = "Andrew"
    val length = name.length
    println(length) // 6, because there are 6 letters
}

Convert a string to uppercase or lowercase:

fun main() {
    val original = "Hello"
    println(original.uppercase()) // HELLO
    println(original.lowercase()) // hello
}

Remove spaces at the edges (very useful when reading input from the keyboard):

fun main() {
    val messy = "   hello   "
    println(messy.trim()) // "hello"
}

Each such function returns a new string; the old string does not change.

8. String templates

$name: substituting values into a string

When there are many concatenations, the string starts to look like a mess of quotes, plus signs, and spaces. Kotlin offers a very practical syntax — string templates: inside a string you can write $name, and Kotlin will substitute the variable’s value. This is part of the language’s basic syntax.

You just need to write the variable name with a dollar sign, and Kotlin will substitute its value right into the text:

fun main() {
    val cafe = "Byte & Coffee"
    val item = "Latte"
    val price = 180

    println("=== $cafe ===")    // === Byte & Coffee ===
    println("Item: $item")   // Item: Latte
    println("Price: $price ₣ ")   // Price: 180
}

Agree, it is easier on the eyes — for you and for whoever will read your code.

${expr}: inserting expressions

$name works when you need to substitute a simple name (a variable). But often you want to substitute the result of a calculation: a sum, a product, an expression with parentheses. For this, the ${...} form is used.

Just add curly braces, and inside them you can write any expressions:

fun main() {
    val item = "Latte"
    val price = 180
    val count = 2

    println("Item: $item")
    println("Price for 1: $price ₣ ")
    println("Quantity: $count")
    println("Total: ${price * count} ₣ ") // Total: 360 ₣
}

Here, inside ${...} there is a regular expression price * count, which you can already read thanks to the previous lecture about Int.

Concatenation vs templates

When should you choose +, and when templates? In most cases, templates are more convenient. Kotlin even emphasizes this idea in its style recommendations: curly braces in templates should be used for expressions, while a simple variable should be inserted as $name.

Task Concatenation + String templates
Insert a variable
"Hello, " + name
"Hello, $name"
Insert an expression
"Total: " + (a + b)
"Total: ${a + b}"
Don’t forget spaces You need to manually track " " Usually fewer “joins,” easier to notice
Readability Decreases with long strings Usually higher

Concatenation is not forbidden and is sometimes appropriate, especially if you build a string from many pieces step by step. But for typical user messages, templates are almost always simpler.

1
Task
Kotlin SELF, level 2, lesson 2
Locked
Chat greeting
Chat greeting
1
Task
Kotlin SELF, level 2, lesson 2
Locked
Nickname under the magnifying glass
Nickname under the magnifying glass
1
Task
Kotlin SELF, level 2, lesson 2
Locked
The concatenation trap
The concatenation trap
1
Task
Kotlin SELF, level 2, lesson 2
Locked
Cafe receipt
Cafe receipt
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION