首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在逗号分隔字符串中添加"and“

如何在逗号分隔字符串中添加"and“
EN

Stack Overflow用户
提问于 2016-02-18 18:06:16
回答 2查看 348关注 0票数 0

如果我有一个类似于"one, two, three"的字符串,那么如何将它转换为"one, two, and three"

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-18 19:01:33

下面是一种处理有1,2,3+单词的情况的方法:

代码语言:javascript
复制
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"
票数 0
EN

Stack Overflow用户

发布于 2016-02-18 18:23:43

试试这个:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35489140

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档