如何添加"和"以逗号分隔的字符串

时间:2016-02-18 18:06:16

标签: groovy

如果我有一个像"one, two, three"这样的字符串,可以将它转换为"one, two, and three"

如果字符串只包含一个项目,则不需要and

2 个答案:

答案 0 :(得分:1)

试试这个:

def fun(s) {
  def words = s.split(', ')
  words.size() == 1 ? words.head() : words.init().join(', ') + ', and ' + words.last()
}

assert fun("one, two, three") == "one, two, and three"
assert fun("one") == "one"

答案 1 :(得分:0)

这是一种处理1,2,3个字的情况的方法:

def doIt(string) {
    def elements = string.split(', ')

    switch(elements.size()) {
        case 0:
            ''
            break
        case 1: 
            elements[0]
            break
        case 2:
            elements.join(" and ")
            break
        default:
            new StringBuilder().with {
                append elements.take(Math.max(elements.size() - 1, 1)).join(', ')
                append ", and "
                append elements.last()
            }.toString()
            break
    }
}

assert doIt("one, two, three, four") == "one, two, three, and four"
assert doIt("one, two, three") == "one, two, and three"
assert doIt("one, two") == "one and two"
assert doIt("one") == "one"