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;
}
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
}
For those using Jetpack Compose, you should use Compose's String.capitalize(locale: Locale), instead of Kotlin's, as follows:
import androidx.compose.ui.text.capitalize
import androidx.compose.ui.text.intl.Locale
Text("my text".capitalize(Locale.current)) // capitalizes first letter
Text("my text".toUpperCase(Locale.current)) // all caps
//Capitalize the first letter of the words
public String Capitalize(String str) {
String[] arr = str.split(" "); //convert String to StringArray
StringBuilder stringBuilder = new StringBuilder();
for (String w : arr) {
if (w.length() > 1) {
stringBuilder.append(w.substring(0, 1).toUpperCase(Locale.US) + w.substring(1).toLowerCase(Locale.US) + " ");
}
}
return stringBuilder.toString().trim();
}