Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

I am having a list of String letterString

List<String> letterString = ['Jan', 'Feb', 'Mar'];

Below is teh output I want :

String outputString = 'Jan,Feb,Mar';

This is what I have done :

  String outputString = '';
  for(String s : letterString) {
      outputString += s+',';
  }

But outputString is Jan,Feb,Mar, with an extra , at an end of string.

share|improve this question
    
Can't you use the traditional "for loop" to solve this ?. salesforce.com/us/developer/docs/apexcode/Content/… –  ZenSeeker Dec 21 '14 at 15:57
    
@UnderDog : As you can see I was trying to solve this by using the traditional for loop.I was not aware of ` string.Join()`. But if it can be done by using 1 line of code, why to go 5 lines of code. :) –  SFDC Geek Dec 21 '14 at 16:20
    
I meant this form of "for loop" for (init_stmt; exit_condition; increment_stmt) { code_block } and NOT for (variable : list_or_set) { code_block } –  ZenSeeker Dec 21 '14 at 16:24

1 Answer 1

up vote 9 down vote accepted

This is as expected. The comma is still being appended in the last iteration of the loop even though there are no further records to be appended.

You could do some changes around the index being added or remove the trailing comma after the loop to make it work.

However, you could save yourself the hassle and use the built in String.join(Object, String) method.

String outputString = String.join(letterString, ',');
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.