简体   繁体   English

使用 Groovy 脚本连接字符串

[英]Concat String using Groovy Script

I am new to groovy.我是 groovy 的新手。 I have a csv file which has only 1 field.我有一个只有 1 个字段的 csv 文件。 I need to concat the fields with a comma (,).我需要用逗号 (,) 连接字段。 Its a very simple requirement, but what I am not sure is do we need to create a Array list or there is a simpler way to achieve this?这是一个非常简单的要求,但我不确定是我们需要创建一个数组列表还是有更简单的方法来实现这一点?

Input:输入:

ABC
XYZ
123 

Output: ABC,XYZ,123输出: ABC,XYZ,123

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message) {
    //Body 

    def body = message.getBody();
    def userlist = new ArrayList<body>()
    userlist.join(",");
    return(userlist);
}

You could simply use replaceAll() method您可以简单地使用replaceAll()方法

def data = '''\
ABC
XYZ
123'''

def output = data.replaceAll( /\n/, ',' )
assert output == 'ABC,XYZ,123'

you could use CharSequence.readLines() to split multi-line string to an array of single-line strings and then join them您可以使用CharSequence.readLines()将多行字符串拆分为单行字符串数组,然后加入它们

def data = '''\
ABC
XYZ
123'''

def output = data.readLines().join(',')
assert output == 'ABC,XYZ,123'

Thanks all for your help.感谢你的帮助。 Modified the code as below.修改代码如下。 Both of the below codes work now by adding toString and the encoding.下面的两个代码现在都可以通过添加 toString 和编码来工作。 1) 1)

        def Message processData(Message message) {
    //Body 
       def body = message.getBody().toString("UTF-8");
       output = body.readLines().join(',')
       message.setBody(output);
       return message;
 def Message processData(Message message) {
//Body 
   def body = message.getBody().toString("UTF-8");
   output = body.replaceAll( /\n/, ',' )
   message.setBody(output);
   return message;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM