Yes/no-question: Is there a Groovy GDK function to capitalize the first character of a string?
I'm looking for a Groovy equivalent of Perl's ucfirst(..) or Apache Commons StringUtils.capitalize(str) (the latter capitalizes the first letter of all words in the input string).
I'm currently coding this by hand using ..
str = str[0].toUpperCase() + str[1 .. str.size() - 1]
.. which works, but I assume there is a more Groovy way to do it. I'd imagine ucfirst(..) being a more common operation than say center(..) which is a standard method in the Groovy GDK (see http://groovy.codehaus.org/groovy-jdk/java/lang/String.html).
As of Groovy 1.8.2 (released way back in September 2011),
capitalize()
is a built-in enhancement toCharSequence
whichString
implements.No, nothing built directly into the language.
There are a couple of more groovy ways to do what you're asking though (if you don't want to use StringUtils in the Java idiomatic way as Vladimir suggests).
You can simplify your method using a negative value in the second half of your range:
Or you can use an import static to make it look like a native method:
You can also modify the metaClass to have all of StringUtils methods right on it, so it looks like a GDK method:
If you wanted to take it a step further and capitalize each word, you can use something like this:
well you can try this:
"hey this is a string".split(' ').collect{it.capitalize()}.join(' ')
or may be this:
char c = ' ' "hey this is a string".collect{ c = c==' '?it.capitalize():it }.join()
To make it available globally in your app ,just initialise this block at start up
String.metaClass.capitalize = { delegate[0].toUpperCase()+delegate[1..-1] }
I'm not aware of any such method, but a workaround is to directly use the Apache Commons library in your Groovy code:
It makes your Groovy code a bit Java-ish (some may not like it) but it does the job.
IMO the great advantage of Groovy is that you can very easily leverage all the Java libraries you normally use with a more traditional Java code base.