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.
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"
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.