Kotlin Training Program

DOWNLOAD APP

FEEDBACK

Case Conversions

Now that we have seen Char case conversions, it is very easy to case convert the entire string. To convert a string to uppercase, we iterate over it and replace the lowercase characters with their corresponding uppercase characters.

Implementation

 fun String.uppercase(): String {
    val array = toCharArray()
    array.forEachIndexed { index, c ->
        if (c in 'a'..'z') {
            array[index] = Char(c.code - 32)
        }
    }
    return String(array)
}
 

Alternatively, we can also use the previously defined Char#uppercaseChar() function :

 fun String.uppercase(): String {
    val array = toCharArray()
    array.forEachIndexed { index, c ->
        array[index] = c.uppercaseChar()
    }
    return String(array)
}