Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy GDK equivalent of Apache Commons StringUtils.capitalize(str) or Perl's ucfirst(str)

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).

like image 344
knorv Avatar asked Mar 25 '09 14:03

knorv


People also ask

What is StringUtils?

StringUtils handles null input Strings quietly. That is to say that a null input will return null . Where a boolean or int is being returned details vary by method. A side effect of the null handling is that a NullPointerException should be considered a bug in StringUtils .

What is StringUtils substring?

Overview. In Java, substring() is a static method of the StringUtils class that returns the string between the given start and end index. Negative start and end index positions can be used to specify offsets relative to the end of the string.

Why do we use StringUtils?

Most common use of StringUtils is in web projects (when you want to check for blank or null strings, checking if a string is number, splitting strings with some token). StringUtils helps to get rid of those nasty NumberFormat and Null exceptions. But StringUtils can be used anywhere String is used.

What is StringUtils trimToNull?

trimToNull() is a static method of the StringUtils class that is used to remove the control characters from both ends of the input string. The method returns null if the input string is null . The method returns null if the input string results in an empty string after the trim operation.


1 Answers

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:

def str = "foo"

assert "Foo" == str[0].toUpperCase() + str[1..-1]

Or you can use an import static to make it look like a native method:

import static org.apache.commons.lang.StringUtils.*

assert "Foo" == capitalize("foo")

You can also modify the metaClass to have all of StringUtils methods right on it, so it looks like a GDK method:

import org.apache.commons.lang.StringUtils

String.metaClass.mixin StringUtils

assert "Foo" == "foo".capitalize()
like image 84
Ted Naleid Avatar answered Sep 19 '22 05:09

Ted Naleid