• Post Reply Bookmark Topic Watch Topic
  • New Topic

best way to remove the last comma  RSS feed

 
Celinio Fernandes
Ranch Hand
Posts: 549
Eclipse IDE Google Web Toolkit Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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


 
Stuart Gray
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Steve Morrow
Ranch Hand
Posts: 657
Clojure Spring VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'd also recommend using a StringBuffer/StringBuilder if you're going to be repeatedly concatenating a string...
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!