string Groovy 字符串连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1010698/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:28:16  来源:igfitidea点击:

Groovy String Concatenation

stringgroovy

提问by XanderLynn

Current code:

当前代码:

row.column.each(){column ->
    println column.attributes()['name']
    println column.value()
}

Columnis a Nodethat has a single attribute and a single value. I am parsing an xml to input create insert statements into access. Is there a Groovy way to create the following structured statement:

ColumnNode具有单个属性和单个值的 a 。我正在解析一个 xml 以将创建插入语句输入到访问中。是否有 Groovy 方法来创建以下结构化语句:

Insert INTO tablename (col1, col2, col3) VALUES (1,2,3)

I am currently storing the attribute and value to separate arrays then popping them into the correct order.

我目前正在将属性和值存储到单独的数组中,然后将它们按正确的顺序弹出。

回答by Ted Naleid

I think it can be a lot easier in groovy than the currently accepted answer. The collect and join methods are built for this kind of thing. Join automatically takes care of concatenation and also does not put the trailing comma on the string

我认为在 groovy 中它比目前接受的答案容易得多。collect 和 join 方法就是为这种事情而构建的。Join 会自动处理连接,并且不会将尾随逗号放在字符串上

def names = row.column.collect { it.attributes()['name'] }.join(",")
def values = row.column.collect { it.values() }.join(",")
def result = "INSERT INTO tablename($names) VALUES($values)"

回答by Ben Williams

You could just use two StringBuilders. Something like this, which is rough and untested:

您可以只使用两个 StringBuilder。像这样的东西,这是粗糙且未经测试的:

def columns = new StringBuilder("Insert INTO tablename(")
def values = new StringBuilder("VALUES (")
row.column.each() { column ->
    columns.append(column.attributes()['name'])
    columns.append(", ")
    values.append(column.value())
    values.append(", ")
}
// chop off the trailing commas, add the closing parens
columns = columns.substring(0, columns.length() - 2)
columns.append(") ")
values = values.substring(0, values.length() - 2)
values.append(")")

columns.append(values)
def result = columns.toString()

You can find all sorts of Groovy string manipulation operators here.

您可以在此处找到各种 Groovy 字符串操作运算符。