Grails在行中将每个单词设为大写

时间:2013-05-27 16:15:06

标签: grails

我希望将每个单词的第一个字符作为大写,并将字符重新作为小写。以下代码打印与原始字符串相同。怎么能使这个工作?

def name = "hello world grails"

        println  name.split(" +").each{
             it[0]?.toUpperCase()+it[1..-1]?.toLowerCase()
        }

3 个答案:

答案 0 :(得分:1)

这将完成你的工作:

 ​def name = "hello world grails"

 def newName = ""
 name.split(" ").each { word ->
    newName += word[0].toUpperCase() + word[1..(word.size()-1)].toLowerCase()+" "
 }

 println newName​

答案 1 :(得分:1)

您可以使用在1.7.3版本中添加到Groovy的capitalize()方法:

def name = "hello world grails"
def splitted = name.split("\\s+").collect { it.toLowerCase().capitalize() }
println splitted

如果你想要一个字符串:

println splitted.inject('') { accumulator, current -> accumulator + current + ' ' }.trim()

您的代码也存在问题。使用.each {...}不会“转换”结果列表中的元素,例如

def list = ["Asdf", "XCVB"]
def ret = list.each { return it.toLowerCase() }
println ret == list // true
ret = list.collect { return it.toLowerCase() }
println ret == list // false

答案 2 :(得分:1)

使用以下代码:

def requiredString = org.apache.commons.lang.WordUtils.capitalizeFully('i AM gRooT') // yields 'I Am Groot'

您需要包含Apache Commons Lang作为依赖项。