繁体   English   中英

如何在逗号分隔的字符串中添加“和”

[英]How to add “and” to a comma separated string

如果我有一个字符串,例如"one, two, three"那么将其转换为"one, two, and three" 1、2、3 "one, two, and three"的方式是什么?

如果字符串仅包含一项,则否, and是必需的。

尝试这个 :

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、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"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM