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

Strings and text: the String type, working with strings

Kotlin SELF
레벨 2, 레슨 2
사용 가능

1. Taking a closer look at the String type

The String type is one of the most used types in Kotlin. Possibly the most used one overall. It’s a truly 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 these functions you can do various interesting things.

In addition, all objects in Kotlin (literally all of them) can be converted to String. Or, more correctly, all objects in Kotlin return their textual (string) representation. We will come back to this type more than once (it’s very useful and interesting), but today we will get acquainted 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 following command:

var imya: String
Creating a variable of type String

Where imya 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 imya1: String
    var imya2: String
    var imya3: String
}

2. Assigning values to variables of type String

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

imya = "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 strings of text and must be enclosed in double quotes.

Examples:

Command Note
var name: String = "Ani"
The variable name contains the text Ani
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 all types in Kotlin. So we won’t talk about it anymore.

fun main() {
    var imya1: String = "value1"
    var imya2: String = "value2"
    var imya3: String = "value3"
}
General form of creating and initializing variables
fun main() {
    var name: String = "Ani"
    var city: String = "New York"
    var message: String = "Hello!"
}
Example of a create-and-initialize command

You can change only variables that have a value

The Kotlin compiler will complain if you declare a variable without assigning it any value 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. Or, to make it easier to remember — Con-Cat-e-nation 😆. It’s also often called “joining strings” or even just “adding strings”.

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

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

Examples:

Command Note
val name = "Ani" + "Ani"
name contains the string AniAni
val city = "New York" + "Ani"
city contains the string New YorkAni
val message = "Hello! " + "Ani"
message contains the string Hello! Ani

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

Examples:

fun main() {
    val name = "Ani"                  // name contains the string Ani
    val city = "New York"             // city contains the string New York
    val message = "Hello!" + city + name + city // message contains the string Hello!New YorkAniNew 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 specify one space or several, you just write them in code and wrap them in double quotes. It’s easier than it sounds:

" "
A string containing a single space

By the way, if you leave no space between the quotes at all (write two double quotes in a row), you get the 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 concatenating with other strings, nothing happens. It’s like an analogue of zero, but for strings.

6. Escaping special characters in strings

You already know that strings are wrapped in double quotes. But what if you need to insert quotes into a string? If we write quotes inside a string, won’t the compiler treat them as the end of the string?

Correct. It will. Therefore, quotes inside text are replaced with a 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’s a bit trickier. The \ character is considered a special (control) character inside strings. With its help, you can specify various “non-printable characters” such as newline, tab, etc. And to specify 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)
\\
Literal \
\"
Quotes inside a string

Example:

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

Will output:

// Line 1
// Line 2

7. String’s own 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 learn some of them (the simplest ones). 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(...).

Determine the string length:

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

Convert a string to upper or lower case:

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

Remove spaces at the edges (very useful when reading 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: inserting values into a string

When there are many concatenations, the string starts to look like noodles made of quotes, pluses, and spaces. Kotlin offers a very practical syntax — string templates (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 directly 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’s easier on the eyes. For you, and for anyone who will read your code.

${expr}: inserting expressions

$name works when you need to insert a simple name (a variable). But often you want to insert the result of a computation: a sum, a product, an expression with parentheses. For that, use the form ${...}.

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 per 1: $price ₣ ")
    println("Quantity: $count")
    println("Total: ${price * count} ₣ ") // Total: 360 ₣
}

Here, inside ${...} there is a normal expression price * count, which you already know how to 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 separately in the style recommendations: curly braces in templates should be used for expressions, and 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 must manually watch for " " Usually fewer “joins”, easier to notice
Readability Gets worse 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
과제
Kotlin SELF, 레벨 2, 레슨 2
잠금
채팅 인사말
채팅 인사말
1
과제
Kotlin SELF, 레벨 2, 레슨 2
잠금
닉네임 검사
닉네임 검사
1
과제
Kotlin SELF, 레벨 2, 레슨 2
잠금
문자열 결합의 함정
문자열 결합의 함정
1
과제
Kotlin SELF, 레벨 2, 레슨 2
잠금
카페 영수증
카페 영수증
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION