[英]how to use split and string builder together in groovy
I would like to split the string using a comma and append another string with the split value. 我想用逗号分割字符串,并用分割值附加另一个字符串。
For example, I have a string make=apple,product=iPhone
. 例如,我有一个字符串make=apple,product=iPhone
。 I want to split the string apple, iPhone which I'm doing below. 我想在下面拆分字符串苹果,iPhone。 After splitting I want to append another string in each splitted value. 拆分后,我想在每个拆分后的值中附加另一个字符串。 So my final string should look like this, make=apple-Id=1234,product=iPhone-Id=1234.
因此,我的最终字符串应如下所示: make=apple-Id=1234,product=iPhone-Id=1234.
If I have a single string with no comma, then I would have to display make=apple-Id=1234
如果我有一个没有逗号的字符串,那么我将不得不显示make=apple-Id=1234
def myString = "make=apple,product=iPhone"
def result = myString.split(",")
for( String values : result )
println(values);
I'm able to split it, but struggling to append like how I want. 我能够拆分它,但是却很难像我想要的那样追加。 Can someone suggest what's the right way of doing in groovy? 有人可以建议用Groovy做正确的事情吗?
Thanks. 谢谢。
def s='make=apple,product=iPhone'
println s.split(',').collect{it+'-Id=1234'}.join(',')
result: 结果:
make=apple-Id=1234,product=iPhone-Id=1234
Use the collect method to transform each segment of the split String into what you need. 使用collect方法将拆分后的String的每个段转换为所需的内容。 Then you can combine them back together as a single String with the join method. 然后,您可以使用join方法将它们重新组合为单个String。
def myString = "make=apple,product=iPhone"
def result = myString.split(',').collect { it + '-Id=1234' }.join(',')
assert result == 'make=apple-Id=1234,product=iPhone-Id=1234'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.