1

I want to generate the string as number1, number2, number3 with the following code.

    String accountNumbers = '';
    for(Account Acc: solvAccounts){
        accountNumbers = accountNumbers + '' + Acc.Name + ', ';
    }
    accountNumbers.replace(',','');

But the output I am getting is number1, number2, number3,. need help to remove the extra comma at the end of the string.

2 Answers 2

9

For such purposes I recommend you to use String.join() method, which joins the elements of the specified iterable object, such as a List, into a single String separated by the specified separator:

List<String> accNames = new List<String>();
for (Account acc : solvAccounts) {
    accNames.add(acc.Name);
}
String result = String.join(accName, ', ');
1
1

You can use the removeEnd(substring) method from String class in Apex.

String str = 'number1, number2, number3,';
str = str.removeEnd(',');
system.debug('Str ' + str);

Output : Str number1, number2, number3

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .