views:

351

answers:

8

When you have to loop through a collection and make a string of each data separated by a delimiter, you always end up with an extra delimiter at the end, e.g.

for(String serverId : serverIds) {
 sb.append(serverId);
 sb.append(",");
}

Gives something like : serverId_1, serverId_2, serverId_3,

I would like to delete the last character in the StringBuilder (without converting it because I still need it after this loop).

+8  A: 
sb.deleteCharAt(sb.length()-1) 
Bragboy
Hm ... I missed the delete functions in the javadoc ! aha ) I'm used to look for "remove"Thanks !
Matthew
A: 

http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StringBuilder.html

StringBuilder deleteCharAt(int index) Removes the char at the specified position in this sequence.

sb.deleteCharAt(sb.length() - 1);
org.life.java
+5  A: 

Another solution is:

sb.setLength(sb.length() - 1);
Stephen C
A: 
StringBuilder sb = new StringBuilder();
sb.append("abcdef");
sb.deleteCharAt(sb.length() - 1);
assertEquals(sb.toString(), "abcde");
// true
Antoine
+11  A: 

Others have pointed out the deleteCharAt method, but here's another alternative approach:

String prefix = "";
for (String serverId : serverIds) {
  sb.append(prefix);
  prefix = ",";
  sb.append(serverId);
}

Alternatively, use the Joiner class from Guava :)

Jon Skeet
yes, I think this gonna be a more sophisticated solution
nil
that's what I think in my comment...
Sylvain M
Can't `""` and `","` be `char`s? If StringBuilder is mainly used for performance, why not go all the way?
Coronatus
@Coronatus: No, because "" is the *absence* of any characters, not a single character.
Jon Skeet
A: 

Alternatively,

StringBuilder result = new StringBuilder();
    for(String string : collection) {
        result.append(string);
        result.append(",");
    }
    return result.substring(0, result.length() - 1) ;
Zaki
A: 

Yet another alternative:

public String join(Collection<String> collection, String seperator) {
    if (collection.isEmpty()) return "";

    Iterator<String> iter = collection.iterator();
    StringBuilder sb = new StringBuilder(iter.next());
    while (iter.hasNext()) {
        sb.append(seperator);
        sb.append(iter.next());
    }

    return sb.toString();
}
Jason Day
A: 

The following code runs faster than the jon skeets code . the empty prefix object does unnecessary object creation. jon skeets code takes 86324 nano seconds,while mine takes only 68165 nano seconds.

List<String> l =  Arrays.asList("SURESH1","SURESH2","SURESH4","SURESH5");
StringBuffer  l1 = new StringBuffer();
int sz = l.size(); 
int i=0; long t =
System.nanoTime();
for (String s : l)
{ 
   l1.append(s);     
   if  ( i != sz-1)
        l1.append(",");   i++;
   } 
} 
long t2 = System.nanoTime();
System.out.println ((t2-t)); System.out.println(l1);

// The time taken for the above code is less 68165 nano seconds
SURESH1,SURESH2,SURESH4,SURESH5
Suresh S