Each character in a string has a numbered position known as its index. We access a character by referring to its index number.
Strings use zero-based indexing, so the first character in a string has an index of 0, the second character has an index of 1, etc.
We’re using the .charAt() method with the index to access the character:
val message = "Hello world!"
var c = message.charAt(0)
println(c) // Output: H
c = message.charAt(1)
println(c) // Output: e
println(message.charAt(6)) // Output: w
Whitespaces have indices:
Note that every character inside the quotes (including whitespaces) is part of the string and has its own index. For example, in string "Hello world!", the whitespace is placed on index 5.
You can see that clearly when you run this code:
val message = "Hello world!"
println(s"${message.charAt(4)}${message.charAt(5)}${message.charAt(6)}")
the output is:
o w
Assignment
Follow the Coding Tutorial and let's access some characters!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. Premium is unlimited.