Kotlin Strings
A String is a value that holds text. A String can be measured, read one character at a time, and joined with other strings.
The length of a name
The word length after a dot gives the character count of the string. The name Maya has four characters.
fun main() {
val name = "Maya"
println(name.length)
}Characters by position
Square brackets read the character at one position. Position 0 gives the first letter and position 5 gives the last letter of this word.
fun main() {
val word = "kotlin"
println(word[0])
println(word[5])
}Joining strings with +
The + sign joins two strings end to end. The joined text prints as one line with nothing added between the parts.
fun main() {
val first = "Hello, "
val second = "Ana"
println(first + second)
println("sun" + "shine")
}The last character
The last position of a string is its length minus one. Reading that position gives the final letter.
fun main() {
val word = "garden"
println(word[word.length - 1])
}Example
fun main() {
val city = "Paris"
println(city.length)
println(city[0])
val greeting = "Welcome to " + city
println(greeting)
}Key points
- length: the number of characters in a string.
- Use square brackets with a position to read one character from a string.
- The first character of a string sits at position 0.
- Use + to join two strings into one longer string.
In this example, city holds the text Paris. The length print shows 5 characters. The position print shows P, the character at position 0. The last print joins the greeting text with city and shows Welcome to Paris.
Note
A space inside a string counts as a character in its length.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
What does println("code"[2]) print?