Reputation: 35938
If I have a string like "one, two, three"
what is a way to convert it to "one, two, and three"
If the string contains only one item then no and
is necessary.
Upvotes: 0
Views: 454
Reputation: 9885
Here's a way to handle cases where there are either 1, 2, 3+ words:
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"
Upvotes: 0
Reputation: 11022
try this :
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"
Upvotes: 1