| Author |
best way to remove the last comma
|
Celinio Fernandes
Ranch Hand
Joined: Jun 28, 2003
Posts: 546
|
|
Hi, what is the best way to remove the last comma in my String ? for (int i=0;i<5,i++) { // some pre-treatment here String foo = "hello"; String result += foo + ", "; // and some post-treatment here } result = hello, hello, hello, hello, hello, but I want it to be: result = hello, hello, hello, hello, hello (without the last comma) Thanks
|
SCJP 1.4, SCWCD 1.4, SCBCD 1.3, SCBCD 5
Visit my blog
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
Originally posted by Max longbeach: Hi, what is the best way to remove the last comma in my String ? for (int i=0;i<5,i++) { // some pre-treatment here String foo = "hello"; String result += foo + ", "; // and some post-treatment here } result = hello, hello, hello, hello, hello, but I want it to be: result = hello, hello, hello, hello, hello (without the last comma) Thanks
|
Joanne
|
 |
Stuart Gray
Ranch Hand
Joined: Apr 21, 2005
Posts: 410
|
|
|
|
 |
Joel McNary
Bartender
Joined: Aug 20, 2001
Posts: 1815
|
|
Indeed, the best way to remove it is to not put it in in the first place. But if you need to remove it, you can say: This will chomp the last character in the string.
|
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
|
 |
Steve Morrow
Ranch Hand
Joined: May 22, 2003
Posts: 657
|
|
|
I'd also recommend using a StringBuffer/StringBuilder if you're going to be repeatedly concatenating a string...
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
Look at String.endsWith() too. You might want to check to see if the comma is there before you remove it. Let's look into never adding the extra comma. I see this kind of thing often when building delimited lists like yours: I prefer to shortcut a bit: If you can modify the code that generated the list, see if that helps.
|
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
|
 |
Layne Lund
Ranch Hand
Joined: Dec 06, 2001
Posts: 3061
|
|
My preference is a slight variation of Joanne's suggestion: [ August 12, 2005: Message edited by: Layne Lund ] [ August 12, 2005: Message edited by: Layne Lund ]
|
Java API Documentation
The Java Tutorial
|
 |
Stan James
(instanceof Sidekick)
Ranch Hand
Joined: Jan 29, 2003
Posts: 8791
|
|
|
The old "priming the pump" option. One line of code before the loop eliminates a redundant assignment statement every time through the loop. I like that, too.
|
 |
 |
|
|
subject: best way to remove the last comma
|
|
|