I would like to format a string
in Java .
Example, take the following string
hola munDO.
And let it be like this:
Hola Mundo.
The first letter of each word is capitalized.
I would like to format a string
in Java .
Example, take the following string
hola munDO.
And let it be like this:
Hola Mundo.
The first letter of each word is capitalized.
You can use the class WordUtils that comes in the Apache Commons library
WordUtils.capitalizeFully("hola munDO")
And you will get
Hello World
Or if you do not want to use an external library, you can use the following code:
String source = "hola munDO";
StringBuffer res = new StringBuffer();
String[] strArr = source.split(" ");
for (String str : strArr) {
char[] stringArray = str.trim().toCharArray();
stringArray[0] = Character.toUpperCase(stringArray[0]);
str = new String(stringArray);
res.append(str).append(" ");
}
System.out.print("Resultado: " + res.toString().trim());
use the toLowerCase () method to convert to lowercase, separate words using split (), by having the array with the words you can convert the first letter to uppercase by Character.toUpperCase()
String s = "hola munDO";
String[] palabras = s.toLowerCase().split(" ");
String resultado = "";
Log.i(TAG, "palabras : " + palabras.length );
for (int i = 0; i< palabras.length ; i ++) {
resultado += Character.toUpperCase(palabras[i].charAt(0)) + palabras[i].substring(1) + " ";
}
System.out.println(resultado);
to get
Hola Mundo