我想加入用户输出的字符串列表。每个字符串之间的分隔符应为','
,但分隔符为'and'
的最后一个元素除外。
例如:
def a = ['one', 'two', 'three'];
println a.joinWithDifferentLast(', ', ' and ');
// output: one, two and three
如何在Groovy中实现这样的连接函数?如果它可以处理一个元素(没有分隔符),两个元素(最后一个分隔符)和多个元素的情况,那将会很好。
答案 0 :(得分: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 ' )
答案 1 :(得分: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()
}
}
答案 2 :(得分: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]
}
稍微“逆转”但需要关于列表大小()的安全性