Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing comma from string array

Tags:

java

sql

I want to execute a query like select ID from "xyz_DB"."test" where user in ('a','b')

so the corresponding code is like

String s="(";
for(String user:selUsers){
    s+= " ' " + user + " ', ";
}
s+=")";

Select ID from test where userId in s;

The following code is forming the value of s as ('a','b',) i want to remove the comma after the end of array how to do this ?

like image 929
sarah Avatar asked Jan 02 '26 09:01

sarah


1 Answers

Here is one way to do this:

String s = "(";
boolean first = true;
for(String user : selUsers){
    if (first) {
        first = false;
    } else {
        s += ", ";
    }
    s += " ' " + user + " '";
}
s += ")";

But it is more efficient to use a StringBuilder to assemble a String if there is looping involved.

StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
    if (first) {
        first = false;
    } else {
        sb.append(", ");
    }
    sb.append(" ' ").append(user).append(" '");
}
sb.append(")");
String s = sb.toString();
like image 124
Stephen C Avatar answered Jan 03 '26 21:01

Stephen C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!