Groovy String Concatenation

此生再无相见时 提交于 2020-02-27 23:27:47

问题


Current code:

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

Column is a Node that 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:

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.


回答1:


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

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)"



回答2:


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

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.



来源:https://stackoverflow.com/questions/1010698/groovy-string-concatenation

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!