I need to capitalize a string in Java on Android
I normally use:
public static String ucFirst(String str) {
if (str.isEmpty()) {
return str;
} else {
return Character.toUpperCase(str.charAt(0)) + str.substring(1);
}
}
String ciudad = ucFirst("barcelona") //Barcelona
Is there a function in Java or library that I don't know, to put in lowercase letters etc...?
I understand that there is no such function in native Java.
Since it's something as simple as what you mention in your algorithm, I don't know if it's worth relying on a library or the like to do that. The implementation I came up with in particular is very similar to yours. Only that it is using
substring
and also contemplating the null string. More or less the following:I hope the answer is useful.
Greetings.
To complement @hdlopez's answer, this process should be very simple, the most common would be this function (which includes a validation) where we require to change the first letter to uppercase:
Android is trying not to use the Apache libraries, as happened with the Http class and external libraries to do this, I don't see an option for something so simple.
Another option to ensure always having the first character in uppercase and the others in lowercase is:
Example:
the city value would be:
Barcelona
There are several answers on Stackoverflow on this topic: https://stackoverflow.com/questions/15259774/capitalise-first-letter-in-string-android
Apache Commons Lang has a method called StringUtils
capitalize(String)
that does exactly that. It also has many other methods,you would have to evaluate if adding an extra 2MB to the APK is worth it.. Add about 400KB to your apk.If you want to do it in a single line, you can resort to something like this, which doesn't have the if, and is easier to read:
But this method is probably less efficient than the one in your example.
Keep in mind that if the string is empty/null, an exception will have to be handled. Or use a defensive approach that includes a null/void validation before executing the statement, it will depend on the use case and adding it already removes it from a single line.
I don't think it's recommended to include a library just for capitalization because the process is quite simple, but we have this:
I made a similar answer and they gave me this answer. it worked perfect for me.