Kotlin program to decapitalize the first character of a string

Introduction :

In this post, I will show you two different ways to decapitalize the first character of a string. For example, if the string is ‘TWELVE’, it will change it to ‘tWELVE’.

In the first method, we will pick the first letter, change it to lowercase and add it with the rest of the string. In the second method, we will use Kotlin string predefined method called decapitalize.

Method 1: Decapitalize the first character :

With this method, we will pick the first character of the string, decapitalize it and append it with the rest of the string. The below program uses this method :

fun main() {
    val str = "TWELVE"
    println(str[0].toLowerCase() + str.substring(1))
}

Here, str[0] is the firstcharacter of the string or the character at 0th index. toLowerCase() converts this character to lower case. substring(1) method gets all characters starting from index 1 to the end. Concatenate both will result the below output :

tWELVE

Method 2: Using str.decapitalize() :

decapitalize method is already defined in Kotlin string class. This method returns one copy of the string with its first letter lowercased.

fun main() {
    val str = "TWELVE"
    println(str.decapitalize())
}

It will print tWELVE as the output.

We can also pass one Local value to this function. It will use the local to decapitalize, else it will use the default Local.

You can use any of this methods we have shown. Try it on your own and drop one comment below if you have any question.

Similar tutorials :