2016-02-18 88 views

回答

0

下面就來處理這種情況有兩種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" 
1

試試這個:

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" 

+0

或'def arr = s.tokenize(/,/); arr.size()> 1? (',')'('and'+ arr.last()))。join(/,/):s' :) – dmahapatro

+1

or'input.reverse()。replaceFirst(',',',and' .reverse()';-) –

+0

或的確如此:'input.replaceAll(/(,)(?!.*,)/,'和')'(如果你喜歡你的正則表達式不可讀) ;-) –