![](/img/trans.png)
[英]How to convert string into map having value as a comma separated list? [on hold]
[英]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.