如果我有一个类似于"one, two, three"的字符串,那么如何将它转换为"one, two, and three"
如果字符串只包含一个项,则不需要and。
发布于 2016-02-18 19:01:33
下面是一种处理有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"发布于 2016-02-18 18:23:43
试试这个:
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"
https://stackoverflow.com/questions/35489140
复制相似问题