groovy 将双引号添加到数组中的字符串

wz8daaqr  于 2023-04-05  发布在  其他
关注(0)|答案(2)|浏览(161)
def names = [lucas,Fred, Mary]

for (i in names) {
   println i
}

我想删除白色,并使用groovy为数组中的每个字符串添加双引号。

预期产出:

"lucas",
"Fred",
"Mary"
62lalag4

62lalag41#

我猜如果 names 是一个字符串数组

def names = ["lucas", "Fred", "Mary"]
println names.collect{"\"${it}\""}.join(",\n")
vngu2lb8

vngu2lb82#

你可以用字符串代替数组

def names = "lucas,Fred,Mary"

for (i in names.split(',')) {
   println '"'+i+'"'
}

另一种方法(但可能很棘手,因为你要处理变量):

public class NamesBinding extends Binding{
    @Delegate Binding delegate;
    public Object getVariable(String name) {
        //when variable declared - return the value, otherwise return the quoted name
        return delegate.hasVariable(name) ? delegate.getVariable(name) : "${groovy.json.JsonOutput.toJson(name)}"
    }
}

this.setBinding(new NamesBinding(delegate:this.getBinding()))

def names = [lucas,Fred,Mary]

for (i in names) {
   println i
}

相关问题