Groovy GDK相当于ApacheCommons StringUtils.capitalize(str)或Perl';UCS第一(str)
是/否问题:是否有Groovy GDK函数将字符串的第一个字符大写 我正在寻找与Perl的ucfirst(..)或ApacheCommons StringUtils.capitalize(str)(后者将输入字符串中所有单词的第一个字母大写)等效的Groovy 我目前正在用..手工编写此代码Groovy GDK相当于ApacheCommons StringUtils.capitalize(str)或Perl';UCS第一(str),string,grails,groovy,gdk,String,Grails,Groovy,Gdk,是/否问题:是否有Groovy GDK函数将字符串的第一个字符大写 我正在寻找与Perl的ucfirst(..)或ApacheCommons StringUtils.capitalize(str)(后者将输入字符串中所有单词的第一个字母大写)等效的Groovy 我目前正在用..手工编写此代码 str = str[0].toUpperCase() + str[1 .. str.size() - 1] 。。这是可行的,但我认为有一种更为常规的方法。我认为ucfirst(..)是一种比say cen
str = str[0].toUpperCase() + str[1 .. str.size() - 1]
。。这是可行的,但我认为有一种更为常规的方法。我认为ucfirst(..)是一种比say center(..)更常见的操作,后者是Groovy GDK中的标准方法(请参阅)。我不知道有任何这样的方法,但解决方法是在Groovy代码中直接使用Apache Commons库:
import org.apache.commons.lang.StringUtils
def str = StringUtils.capitalize(input)
它使您的Groovy代码有点Java风格(有些人可能不喜欢),但它确实做到了这一点
在我看来,Groovy的最大优势在于,您可以非常轻松地利用您通常使用的所有Java库和更传统的Java代码库。不,没有任何东西直接内置到该语言中 不过,有两种更为groovy的方法来实现您的要求(如果您不想像Vladimir建议的那样以Java惯用方式使用StringUtils) 您可以使用范围后半部分的负值简化方法:
def str = "foo"
assert "Foo" == str[0].toUpperCase() + str[1..-1]
或者,您可以使用import static使其看起来像本机方法:
import static org.apache.commons.lang.StringUtils.*
assert "Foo" == capitalize("foo")
您还可以修改元类,使其具有所有StringUtils方法,因此它看起来像一个GDK方法:
import org.apache.commons.lang.StringUtils
String.metaClass.mixin StringUtils
assert "Foo" == "foo".capitalize()
要使其在应用程序中全局可用,只需在启动时初始化此块 String.metaClass.capitalize={ 委托[0]。toUpperCase()+委托[1..-1]
}如果您想更进一步,将每个单词大写,您可以使用以下内容:
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(' ')
def words=句子。拆分(“”)
def newStr=[]
words.each{w->
def capW=[w[0].toUpperCase()]
如果(w.长度()>1){
capW你可以试试这个:
“嘿,这是一个字符串”。拆分(“”)。收集{it.capitalize()}.join(“”)
或者可能是:
charc=''
“嘿,这是一根绳子。”收集{
c=c=''?it.capitalize():it
}.join()
def str = "hello world"
str = str.capitalize()
assert "Hello world" == str
Grails用户要注意,如果您在引导中进行混入,可能会让您感到悲伤,请参见: