在String中将String []转换为逗号分隔的字符串

时间:2011-07-08 10:09:54

标签: java

我有一个String[]

String[] name = {"amit", "rahul", "surya"};

我想在IN子句中的sql查询中发送名称作为参数 那么我如何转换成格式

'amit','rahul','surya'

23 个答案:

答案 0 :(得分:178)

要么自己编写一个简单的方法,要么使用其中一种不同的实用程序。

我个人使用apache StringUtils(StringUtils.join

编辑:在Java 8中,您根本不需要这个:

String joined = String.join(",", name);

答案 1 :(得分:77)

Android开发人员可能正在寻找TextUtils.join

Android文档:http://developer.android.com/reference/android/text/TextUtils.html

代码:

String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)

答案 2 :(得分:47)

StringBuilder sb = new StringBuilder();
for (String n : name) { 
    if (sb.length() > 0) sb.append(',');
    sb.append("'").append(n).append("'");
}
return sb.toString();

答案 3 :(得分:37)

简单明了:但需要java8!

  

String result = String.join(",",names);

答案 4 :(得分:30)

if (name.length > 0) {
    StringBuilder nameBuilder = new StringBuilder();

    for (String n : name) {
        nameBuilder.append("'").append(n.replace("'", "\\'")).append("',");
        // can also do the following
        // nameBuilder.append("'").append(n.replace("'", "''")).append("',");
    }

    nameBuilder.deleteCharAt(nameBuilder.length() - 1);

    return nameBuilder.toString();
} else {
    return "";
}

答案 5 :(得分:27)

您还可以使用org.apache.commons.lang.StringUtils API在Java中与字符串数组形成逗号分隔结果。

StringUtils.join(strArr,",");

答案 6 :(得分:9)

如果您已经将Spring Framework作为依赖项,那么您也可以使用非常简单的util方法:

org.springframework.util.StringUtils.arrayToCommaDelimitedString(String[] array)

答案 7 :(得分:7)

您还可以使用Guava库简化它:

String[] name = {"amit", "rahul", "surya"};
String str = "'" + Joiner.on(",").skipNulls().join(name)
    .replace(",", "','") + "'";

答案 8 :(得分:5)

使用StringBuilder并迭代你的String [],并将每个String附加到其中:

public static String convert(String[] name) { 
    StringBuilder sb = new StringBuilder();
    for (String st : name) { 
        sb.append('\'').append(st).append('\'').append(',');
    }
    if (name.length != 0) sb.deleteCharAt(sb.length()-1);
    return sb.toString();
}

答案 9 :(得分:3)

您可以使用一行代码执行此操作:

Arrays.toString(strings).replaceAll("[\\[.\\].\\s+]", "");

答案 10 :(得分:2)

String[] name = {"amit", "rahul", "surya"};


public static String arrayToString(String array[])
{
    if (array.length == 0) return "";
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.length; ++i)
    {
        sb.append(",'").append(array[i]).append("'");
    }
    return sb.substring(1);
}

答案 11 :(得分:2)

我用这个

public static String convertToCommaSeparated(String[] strings) {
    StringBuffer sb = new StringBuffer("");
    for (int i = 0; strings != null && i < strings.length; i++) {
        sb.append(strings[i]);
        if (i < strings.length - 1) {
            sb.append(',');
        }
    }
    return sb.toString();
}

答案 12 :(得分:1)

USE if set >= 10 then LHPLS001 else LHPL001 功能: 例如。

StringUtils.join

答案 13 :(得分:1)

String[] paramIdIdList={"P001","P002","P003"};

StringBuilder builder = new StringBuilder();
            for(String paramId : paramIdIdList) {
                builder.append(paramId+",");
            }
            builder.deleteCharAt(builder.length() -1);
            String paramIds = builder.toString();
System.Out.Println(paramIds );

答案 14 :(得分:1)

由于代码可能会出现诱惑和“酷”,不会对大型字符串集合使用foldreduce ,因为这些会受到{{{ 3}}

String[] strings = { "foo", "bar", "baz" };
Optional<String> result = Arrays.stream(strings)
        .reduce((a, b) -> String.format("%s,%s", a, b));
System.out.println(result.get());

相反,根据其他答案,如果您已有集合,请使用String.join(),否则使用StringBuilder

答案 15 :(得分:0)

以前的Java 8解决方案的扩展

String result = String.join(",", name);

如果需要数组值的前缀或/和后缀

 StringJoiner joiner = new StringJoiner(",");
 for (CharSequence cs: name) {
     joiner.add("'" + cs + "'");
 }
 return joiner.toString();

简单方法概念

  public static String genInValues(String delimiter, String prefix, String suffix, String[] name) {
    StringJoiner joiner = new StringJoiner(delimiter);
    for (CharSequence cs: name) {
      joiner.add(prefix + cs + suffix);
    }
    return joiner.toString();
  }

例如

For Oracle i need "id in (1,2,3,4,5)" 
then use genInValues(",", "", "", name);
But for Postgres i need "id in (values (1),(2),(3),(4),(5))"
then use genInValues(",", "(", ")", name);

答案 16 :(得分:0)

在Java 8中,没有字符串数组和原始对象(Long,Integer等)

List<Long> ids = Arrays.asList(1l, 2l,3l);
ids.stream().map(String::valueOf).collect(Collectors.joining(","))))

在Java 8中,对于objets数组的特定字段(例如,具有2个字段的颜色和速度的汽车)

List<Car> cars= Cars.asList(car1, cars2,car3);
    cars.stream().map(Car::getColor).collect(Collectors.joining(","))))

mapvalueOf合并为无,则表示对象数组的字符串字段

答案 17 :(得分:0)

这将是一种优化的方式

StringBuilder sb = new StringBuilder();
for (String n : arr) { 
    sb.append("'").append(n).append("',");
}
if(sb.length()>0)
    sb.setLength(sbDiscrep.length()-1);
return sb.toString();

答案 18 :(得分:0)

这是一个实用程序方法,用于分割数组并使用

放置自定义分隔符
String.replace(String,String)
Arrays.toString(Object[])

这里是:

public static String toString(String delimiter, Object[]array){
    String s = "";

    // split array
    if (array != null && array.length > 0) {
        s = Arrays.toString(array).replace("[", "").replace("]", "");
    }

    // place delimiter (notice the space in ", ")
    if(delimiter != null){
        s = s.replace(", ", delimiter);
    }

    return s;
}

更改第二个参数类型以适应您的数组类型

答案 19 :(得分:0)

两行(不包括声明;'finalstring'应该最初声明等于空字符串),如果你不太关心垂直间隔for()循环:

for (int i = 0; i<string_array.length; i++) {finalstring += string_array[i]+",";}
finalstring = finalstring.substring(0,finalstring.length()-1);

两行,你已经完成了。 :)

答案 20 :(得分:0)

您可能还希望不为这种简单的操作生成StringBuilder。请注意,为了符合内容,我已将您的数组名称从名称更改为名称

String[] names = {"amit", "rahul", "surya"};

String namesString = "";
int delimeters = (names.size() - 1);
for (String name : names)
    namesString += (delimeters-- > 0) ? "'" + name + "'," : "'" + name + "'";

答案 21 :(得分:0)

String newNameList=null;

 for(int i = name.length;i>=0;i--){
    if(newNameList==null){
        newNameList = "\'" + name[name.length - i] + "\'";
    }
    else{
        newNameList += ",\'" + name[name.length - i] + "\'";
    }
}

答案 22 :(得分:-1)

这对我有帮助!

private static String convertArrayToString(String [] strArray) {
            StringBuilder builder = new StringBuilder();
            for(int i = 0; i<= strArray.length-1; i++) {
                if(i == strArray.length-1) {
                    builder.append("'"+strArray[i]+"'");
                }else {
                    builder.append("'"+strArray[i]+"'"+",");
                }
            }
            return builder.toString();
        }