Kotlin program to Capitalize the first character or letter of a string

How to Capitalize the first character/letter of a string in Kotlin :

In this post, I will show you two different ways to capitalize the first character of a string. If the input string is “hello”, it should print “Hello”.

Method 1: Using character toUpperCase() :

We can get the first character of a string, convert it to uppercase, and concatenate it with the rest of the string. The following functions can be used :

  1. Char.toUpperCase() : It converts one character to upper case.

  2. String.substring(startIndex: Int) : It returns one substring starting from the index startIndex to the end.

Kotlin Program :

The below program illustrates the above example :

fun main() {
    val str = "hello";
    print(str[0].toUpperCase()+str.substring(1))
}

Here, str[0] returns the first character of the string. toUpperCase() converts it to uppercase, and it is concatenated with the substring starting from index 1 to the end.

If the string is already starting with a capital character, it will return that same string. But, if it is an empty string, it will throw one StringIndexOutOfBoundsException.

Method 2: Using str.capitalize() :

Kotlin provides one inbuilt method to make our life easier. It is called capitalize(). You can call this method directly on any string. It returns one new string capitalizing the first character. For example :

fun main() {
    val str = "hello"
    print(str.capitalize())
}

It prints Hello.

Internally, it does the same thing that we did in the first example. It takes the first character, converts it to uppercase, and concatenates it with the rest of the string.

The only advantage is that for an empty string, it returns an empty string without throwing an exception.

If the string starts with a capital character, it returns the same.

Kotlin string capitalize

Similar tutorials :