Groovy GDK相当于Apache Commons StringUtils.capitalize(str)或Perl的ucfirst(str) [英] Groovy GDK equivalent of Apache Commons StringUtils.capitalize(str) or Perl's ucfirst(str)

查看:195
本文介绍了Groovy GDK相当于Apache Commons StringUtils.capitalize(str)或Perl的ucfirst(str)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在寻找一个Groovy GDK函数来大写字符串的第一个字符吗?对于Groovy相当于Perl的ucfirst(..)或Apache Commons的StringUtils.capitalize(str)(后者大写输入字符串中所有单词的首字母)。

  str = str [0] .toUpperCase()+ str [1 .. str.size() -  1] 

..这有效,但我认为有一个更Groovy的方式来做到这一点。我认为ucfirst(..)是比Groovy GDK中的标准方法中心(..)更常见的操作(参见 http://groovy.codehaus.org/groovy-jdk/java/lang/String.html )。


不,没有直接构建到语言中的东西。

有两种更常见的方式可以完成你所要求的事情(如果你不想按照弗拉基米尔的建议以Java惯用方式使用StringUtils) 。

您可以在范围的后半部分使用负值来简化您的方法:

  def str =foo

assertFoo== str [0] .toUpperCase()+ str [1 ..- 1]

或者你可以使用导入静态来使它看起来像一个本地方法:

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

assertFoo==大写(foo)

您也可以修改metaClass以使所有的StringUtils方法正确,因此它看起来像一个GDK方法:

  import org.apache.commons.lang.StringUtils 

String.metaClass.mixin StringUtils

断言Foo==foo.capitalize()


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

解决方案

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

这篇关于Groovy GDK相当于Apache Commons StringUtils.capitalize(str)或Perl的ucfirst(str)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆