开发者

removing comma from string array

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+=")";

Se开发者_C百科lect 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 ?


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


This does the trick.

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

if (selUsers.size() > 0)
    s = s.substring(2);

s = "(" + s + ")";

But, a few pointers:

  • When concatenating strings like this, you are advised to work with StringBuilder and append.
  • If this is part of an SQL-query, you probably want to sanitize the user-names. See xkcd: Exploits of a Mom for an explanation.

For fun, a variation of Stephen C's answer:

StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
    if (!first || (first = false))
        sb.append(", ");
    sb.append('\'').append(user).append('\'');
}
sb.append(')');

you could even do the loop it like this :-)

for(String user : selUsers)
    sb.append(!first || (first=false) ? ", \'" : "\'").append(user).append('\'');


Use the 'old style' of loop where you have the index, then you add the comma on every username except the last:

    String[] selUsers = {"a", "b", "c"};
    String s="("; 
    for(int i = 0; i < selUsers.length; i++){
        s+= " ' " + selUsers[i] + " ' ";  
        if(i < selUsers.length -1){
            s +=" , ";
        }
    }
    s+=")";

But as others already mentioned, use StringBuffer when concatenating strings:

    String[] selUsers = {"a", "b", "c"};
    StringBuffer s = new StringBuffer("("); 
    for(int i = 0; i < selUsers.length; i++){
        s.append(" ' " + selUsers[i] + " ' ");  
        if(i < selUsers.length -1){
            s.append(" , ");
        }
    }
    s.append(")");


Use StringUtils.join from apache commons.


Prior to adding the trailing ')' I'd strip off the last character of the string if it's a comma, or perhaps just replace the trailing comma with a right parenthesis - in pseudo-code, something like

if s.last == ',' then
  s = s.left(s.length() - 1);
end if;

s = s + ')';

or

if s.last == ',' then
  s.last = ')';
else
  s = s + ')';
end if;

Share and enjoy.


i would do s+= " ,'" + user + "'"; (place the comma before the value) and add a counter to the loop where i just do s = "'" + user + "'"; if the counter is 1 (or 0, depending on where you start to count).


(N.B. - I'm not a Java guy, so the syntax may be wrong here - apologies if it is).

If selUsers is an array, why not do:

selUsers.join(',');

This should do what you want.

EDIT:

Looks like I was wrong - I figured Java had this functionality built-in. Looks like the Apache project has something that does what I meant, though. Check out this SO answer: Java: function for arrays like PHP's join()?


I fully support Stephen C's answer - that's the one I wanted to suggest aswell: simply avoid adding the additional comma.

But in your special case, the following should work too:

s = s.replace(", \\)", ")");

It simply replaces the substring ", )" with a single bracket ")".


Java 1.4+

s = s.replaceFirst("\\, \\)$", ")");

Edited: I forgot last space before parethesis


StringBuilder has a perfectly good append(int) overload.

String [] array = {"1","2","3" ...}; 
StringBuilder builder = new StringBuilder(); 
 builder.append(s + "( ")
for(String i : array) 
{ 
    if(builder.length() != 0) 
        builder.append(","); 
    builder.append(i); 
} 
builder.append(" )")

Answer shamelessly copied from here

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜