我有一个字符串/sample/data
。当我使用split
分割时,我得到以下结果,
["","sample","data"]
我想忽略空字符串。所以我尝试了以下代码,
"/sample/data".split('/').findAll(it != "")
它给了我一个错误“cannot call String[] findAll with argument bool
”。
如何分割并获取没有空字符串的List?
你可以这样做:
println "/sample/data".split('/').findAll {it}
findAll {it}
将获取所有非空值。
split方法返回数组。如果需要List,请使用tokenize
"/sample/data".tokenize('/')
在这种情况下你也不需要使用findAll。
Parens会工作(见问题评论)。所以你的解决方案已经接近了:
"/a/b".split("/").findAll()
因为大多数Groovy函数都具有零arity,它将使用标识闭包调用该函数。由于空字符串被认为是假的,因此会将其过滤掉。