If we have a String in Kotlin or in Java in Android and we need to capitalize the first letter of the string, we don’t have any built-in method for the purpose. You can use the following methods to capitalize the first letter of String in Android in both Java & Kotlin.
Capitalize First Letter of String in Java
public static String capitalizeString(String str) {
String retStr = str;
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1);
}catch (Exception e){}
return retStr;
}
Capitalize First Letter of String in Kotlin
fun capitalizeString(str: String): String {
var retStr = str
try { // We can face index out of bound exception if the string is null
retStr = str.substring(0, 1).toUpperCase() + str.substring(1)
} catch (e: Exception) {
}
return retStr
}
Just pass your String as a Parameter and retrieve the first letter capitalized String in java & Kotlin.
Capitalize Sentences in EditText While Taking Input
We can also capitalize sentences while taking input in EditText in android. But in this scenario user can still have a control to turn it back to a small letter from the soft keyboard. Anyhow you can set capitalize sentences by using textCapSentences input type in EditText in the following way.
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Enter Your Text"
android:inputType="textCapSentences"/>
It shows capitalized sentences in the following way.

That’s it. Enjoy 🙂