Search code examples
kotlin

How to capitalize the first character of a string in Kotlin while ignoring non-letter characters?


I'm using replaceFirstChar() and uppercase() to convert the first character of a string to uppercase.

But some strings can have punctuation marks, quotes, etc. as the first character. In those cases I want it to ignore them, and replace the first alphanumeric character it finds.

How could I achieve this?

Code

fun main(){    
    println("kotlin".replaceFirstChar       { it.uppercase() })  // Kotlin
    println("¡kotlin!".replaceFirstChar     { it.uppercase() })  // I need ¡Kotlin!
    println("¿kotlin?".replaceFirstChar     { it.uppercase() })  // I need ¿Kotlin?
    println("\"¿kotlin?\"".replaceFirstChar { it.uppercase() })  // I need "¿Kotlin?"
    println("\"kotlin\"".replaceFirstChar   { it.uppercase() })  // I need "Kotlin"
}

Output

Kotlin
¡kotlin!
¿kotlin?
"¿kotlin?"
"kotlin"

Desired Output

Kotlin
¡Kotlin!
¿Kotlin?
"¿Kotlin?"
"Kotlin"

Solution

  • You could use the following methods (and logic) in your case:

    1. Use the indexOfFirst on your string input with the isLetter method

    2. Only capitalize the character returned by indexOfFirst

    It can look somewhat like this:

     val firstLetterIndex = str.indexOfFirst { it.isLetter() }
     val result = str.substring(0, firstLetterIndex) + str[firstLetterIndex].uppercaseChar() + str.substring(firstLetterIndex + 1)
    

    Obviously, if the strings themselves may not have any letter, you will want to add an if guard after using indexOfFirst to see if it is equal to -1.