In Kotlin, you can access individual characters in a string using the indexing operator []
. Here are a few examples:
val str = "Hello, World!"
// Accessing the first character of the string
val firstChar = str[0] // 'H'
// Accessing the fifth character of the string
val fifthChar = str[4] // 'o'
// Accessing the last character of the string
val lastChar = str[str.length - 1] // '!'
// Modifying a character in the string (this is not possible in a regular string)
val mutableStr = StringBuilder(str)
mutableStr[7] = 'w' // replaces the 'W' in "World" with 'w'
val modifiedStr = mutableStr.toString() // "Hello, world!"
Note that the []
operator returns a Char
value, which is a single Unicode character. If you want to access a substring of the original string, you can use the substring
function, which we discussed (here) earlier:
val str = "Hello, World!"
// Accessing a substring of the original string
val sub = str.substring(7, 12) // "World"
This code extracts the substring “World” from the original string, starting at index 7 (which is the ‘W’ character) and ending at index 12 (which is the last character of the substring, excluding the character at index 12). Note that the second argument to substring
is exclusive, meaning that the character at the second index is not included in the substring.