i have one String[]
String[] name = {\"amit\", \"rahul\", \"surya\"};
i want to send name as parameter in sql query inside IN
Android developers are probably looking for TextUtils.join
Android docs: http://developer.android.com/reference/android/text/TextUtils.html
Code:
String[] name = {"amit", "rahul", "surya"};
TextUtils.join(",",name)
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:
String[] names = {"amit", "rahul", "surya"};
String namesString = "";
int delimeters = (names.size() - 1);
for (String name : names)
namesString += (delimeters-- > 0) ? "'" + name + "'," : "'" + name + "'";
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();
Either write a simple method yourself, or use one of the various utilities out there.
Personally I use apache StringUtils (StringUtils.join)
edit: in Java 8, you don't need this at all anymore:
String joined = String.join(",", name);
Extention for prior Java 8 solution
String result = String.join(",", name);
If you need prefix or/ and suffix for array values
StringJoiner joiner = new StringJoiner(",");
for (CharSequence cs: name) {
joiner.add("'" + cs + "'");
}
return joiner.toString();
Or simple method concept
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 example
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);
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
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.