1

我想加入一个字符串列表以供用户输出。每个字符串之间的分隔符应为 a ',',但分隔符应为 的最后一个元素除外'and'

例如:

def a = ['one', 'two', 'three'];
println a.joinWithDifferentLast(', ', ' and ');
// output: one, two and three

如何在 Groovy 中实现这样的连接功能?如果它可以处理一个元素(无分隔符)、两个元素(最后一个分隔符)和多个元素的情况,那就太好了。

4

3 回答 3

4

你也可以这样做:

def joinWithDifferentLast( List list, String others, String last ) {
  def start = list.take( list.size() - 1 ).join( others )
  def end   = list.drop( list.size() - 1 )[ 0 ]
  if( start ) {
    [ start, last, end ].join()
  }
  else {
    end as String ?: ''
  }
}

assert ''           == joinWithDifferentLast( [],          ', ', ' and ' )
assert '1'          == joinWithDifferentLast( [ 1 ],       ', ', ' and ' )
assert '1 and 2'    == joinWithDifferentLast( [ 1, 2 ],    ', ', ' and ' )
assert '1, 2 and 3' == joinWithDifferentLast( [ 1, 2, 3 ], ', ', ' and ' )
于 2013-02-15T11:25:26.767 回答
2

为了好玩,我试着让一些东西更容易阅读:

def static joinWithDifferentLast(List list, String firstJoin, String lastJoin) {
    switch (list?.size() ?: 0) {
        case 0:
            return ''
        case 1:
            return list.head() as String
        default:
            return list.init().join(firstJoin) + lastJoin + list.last()
    }
}
于 2016-04-29T20:32:30.967 回答
0
List.metaClass.joinWithDifferentLast { a, b ->
    delegate.join(a).reverse().replaceFirst(a.reverse(),b.reverse()).reverse()
}

def a = ['one', 'two', 'three'];
println a.joinWithDifferentLast(',',' and ') //prints one,two and three

assert ''           == [].joinWithDifferentLast(' , ', ' and ' )
assert '1'          == [ 1 ].joinWithDifferentLast( ', ', ' and ' )
assert '1 and 2'    == [ 1, 2 ].joinWithDifferentLast( ', ', ' and ' )
assert '1, 2 and 3' == [ 1, 2, 3 ].joinWithDifferentLast(', ', ' and ' ) 
assert '1 %ac 2 %ac 3 %ac 4 %ac 5 %bi 6' == [ 1, 2, 3, 4, 5, 6 ].joinWithDifferentLast(' %ac ', ' %bi ' )

将是我的第一个蛮力和幼稚(但已纠正)的猜测:-D

List.metaClass.joinWithDifferentLast { a, b ->
    def l = delegate.size() 
    delegate[0..l-2].join(a) + b + delegate[l-1]
}

少一点“反转”,但需要对列表的 size() 进行安全化

于 2013-02-15T11:14:28.933 回答