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

时间:2021-01-21 00:23:16

i have one String[]

我有一个String []

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

i want to send name as parameter in sql query inside IN clause so how do i convert into a format

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

'amit','rahul','surya'

20 个解决方案

#1


26  

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 "";
}

#2


140  

Either write a simple method yourself, or use one of the various utilities out there.

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

Personally I use apache StringUtils (StringUtils.join)

我个人使用apache StringUtils(StringUtils.join)

edit: in Java 8, you don't need this at all anymore:

编辑:在Java 8中,您根本不再需要它:

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

#3


66  

Android developers are probably looking for TextUtils.join

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

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

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

Code:

码:

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

#4


47  

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

#5


26  

You can also use org.apache.commons.lang.StringUtils API to form a comma separated result from string array in Java.

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

StringUtils.join(strArr,",");

StringUtils.join(strArr, “”);

#6


17  

Nice and simple: but java8 required!

好又简单:但需要java8!

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

String result = String.join(“,”,names);

#7


9  

If you already have Spring Framework as a dependency, you could also use the very simple util method:

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

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

#8


6  

You could also simplify it using the Guava library:

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

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

#9


5  

use StringBuilder and iterate over your String[], and append each String into it:

使用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();
}

#10


3  

You can do this with one line of code:

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

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

#11


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);
}

#12


2  

i use this

我用这个

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();
}

#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  

As tempting and "cool" as the code may appear, do not use fold or reduce on large collections of strings, as these will suffer from the string concatenation problem

由于代码可能出现诱惑和“酷”,不要在大型​​字符串集合上使用fold或reduce,因为这些将受到字符串连接问题的影响

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());

Instead, as per other answers, use String.join() if you already have a collection, or a StringBuilder if not.

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

#15


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] + "\'";
    }
}

#16


0  

You may also want not to spawn StringBuilder for such simple operation. Please note that I've changed name of your array from name to names for sake of content conformity:

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

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

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

#17


0  

Two lines (excluding declarations; 'finalstring' should be initially declared equal to an empty string), if you don't care a lot about vertically spacing the for() loop:

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

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

Two lines, you're done. :)

两行,你完成了。 :)

#18


0  

here is a Utility method to split an array and put your custom delimiter, using

这是一个实用的方法来分割数组并使用自定义分隔符

String.replace(String,String)
Arrays.toString(Object[])

here it is :

这里是 :

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;
}

change the second argument type to suite your array type

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

#19


0  

This would be an optimized way of doing it

这将是一种优化的方式

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();

#20


-1  

USE StringUtils.join function: E.g.

USE StringUtils.join函数:例如

String myCsvString = StringUtils.join(myList, ",")

#1


26  

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 "";
}

#2


140  

Either write a simple method yourself, or use one of the various utilities out there.

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

Personally I use apache StringUtils (StringUtils.join)

我个人使用apache StringUtils(StringUtils.join)

edit: in Java 8, you don't need this at all anymore:

编辑:在Java 8中,您根本不再需要它:

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

#3


66  

Android developers are probably looking for TextUtils.join

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

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

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

Code:

码:

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

#4


47  

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

#5


26  

You can also use org.apache.commons.lang.StringUtils API to form a comma separated result from string array in Java.

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

StringUtils.join(strArr,",");

StringUtils.join(strArr, “”);

#6


17  

Nice and simple: but java8 required!

好又简单:但需要java8!

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

String result = String.join(“,”,names);

#7


9  

If you already have Spring Framework as a dependency, you could also use the very simple util method:

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

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

#8


6  

You could also simplify it using the Guava library:

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

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

#9


5  

use StringBuilder and iterate over your String[], and append each String into it:

使用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();
}

#10


3  

You can do this with one line of code:

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

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

#11


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);
}

#12


2  

i use this

我用这个

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();
}

#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  

As tempting and "cool" as the code may appear, do not use fold or reduce on large collections of strings, as these will suffer from the string concatenation problem

由于代码可能出现诱惑和“酷”,不要在大型​​字符串集合上使用fold或reduce,因为这些将受到字符串连接问题的影响

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());

Instead, as per other answers, use String.join() if you already have a collection, or a StringBuilder if not.

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

#15


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] + "\'";
    }
}

#16


0  

You may also want not to spawn StringBuilder for such simple operation. Please note that I've changed name of your array from name to names for sake of content conformity:

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

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

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

#17


0  

Two lines (excluding declarations; 'finalstring' should be initially declared equal to an empty string), if you don't care a lot about vertically spacing the for() loop:

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

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

Two lines, you're done. :)

两行,你完成了。 :)

#18


0  

here is a Utility method to split an array and put your custom delimiter, using

这是一个实用的方法来分割数组并使用自定义分隔符

String.replace(String,String)
Arrays.toString(Object[])

here it is :

这里是 :

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;
}

change the second argument type to suite your array type

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

#19


0  

This would be an optimized way of doing it

这将是一种优化的方式

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();

#20


-1  

USE StringUtils.join function: E.g.

USE StringUtils.join函数:例如

String myCsvString = StringUtils.join(myList, ",")