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

Strings and text: the String type, working with strings

Open

1. Taking a closer look at the String type

The String type is one of the most commonly used types in Kotlin. Possibly the most commonly used one. It’s a great type, because you can store text in variables of this type. And also, unlike the Int and Double types, objects of type String have a lot 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 the String type. Or, to be more accurate, all objects in Kotlin return their textual (string) representation. We will come back to this type more than once (it’s really useful and interesting), but today we’ll get familiar with the 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 statement:

var name: String
Creating a variable of type String

Where name is the variable name.

Examples:

Statement 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 the Int and Double types, you can create multiple variables of type String.

In Kotlin, the comma-separated declaration used in Java (String a, b;) is 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 statement:

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

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:

Statement 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 the Int and Double types, 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 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 = "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 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’s a very interesting and simple thing you can do with strings in Kotlin: you can join them together. This operation is called concatenation. It’s also often called “string joining” or even just “string addition.”

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

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

Examples:

Statement 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, and you can also concatenate strings and 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’s missing spaces. To specify one space or several, you just need to 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 at all between the quotes (write two double quotes in a row), you get what is called an “empty string”:

""
Empty string

On the one hand, it exists, but on the other hand, when you print it, nothing is displayed. And when you join it with other strings, nothing happens. It’s like the analogue of zero, but for strings.

6. Escaping special characters in strings

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

Correct—it will. That’s why quotes inside text are replaced with the character sequence \". 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 it, you can specify various “non-printing characters” such as newline, tab, etc. And to specify the \ character itself, you need to write it twice.

Here are the 4 most common sequences:

Sequence Meaning
\n
Newline
\t
Tab (indent)
\\
Literal \
\"
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 learn about some of 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(...).

Get the length of a string:

fun main() {
    val name = "Andrey"
    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 lots of concatenations, a 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 value of the variable. 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—this is easier on the eyes. For you, and for anyone who will read your code.

${expr}: inserting expressions

$name works when you want 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 that, you use the ${...} form.

Just add curly braces, and inside 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 ${...} is a regular 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 should you choose templates? In most cases, templates are more convenient. Kotlin even emphasizes this idea in its style guidelines: it’s recommended to use curly braces in templates for expressions, and to insert a simple variable 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 have to manually watch for " " Usually fewer “joins,” easier to spot
Readability Drops with long strings Usually higher

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

1
Task
Kotlin SELF,  2 level,  2 lecture
Locked
Chat greeting
Chat greeting
1
Task
Kotlin SELF,  2 level,  2 lecture
Locked
Nickname under the magnifying glass
Nickname under the magnifying glass
1
Task
Kotlin SELF,  2 level,  2 lecture
Locked
The concatenation trap
The concatenation trap
1
Task
Kotlin SELF,  2 level,  2 lecture
Locked
Cafe receipt
Cafe receipt
Комментарии
  • популярные
  • новые
  • старые
Для того, чтобы оставить комментарий Вы должны sign in
This page has no comments yet