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

孤者浪人 提交于 2019-12-04 04:13:01

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

I'm not aware of any such method, but a workaround is to directly use the Apache Commons library in your Groovy code:

import org.apache.commons.lang.StringUtils

def str = StringUtils.capitalize(input)

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.

To make it available globally in your app ,just initialise this block at start up

String.metaClass.capitalize = { delegate[0].toUpperCase()+delegate[1..-1] }

If you wanted to take it a step further and capitalize each word, you can use something like this:

def words = sentence.split(" ")
def newStr = []
words.each { w ->
    def capW = [w[0].toUpperCase()]
    if (w.length() > 1) {
        capW << w[1..-1].toLowerCase()
    }
    newStr << capW.join()
}
return newStr.join(' ')

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

As of Groovy 1.8.2 (released way back in September 2011), capitalize() is a built-in enhancement to CharSequence which String implements.

def str = "hello world"
str = str.capitalize()
assert "Hello world" == str
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!