0

I have string like this.

,mon,,tue,wed,,,thu,

I want out out put like this.

mon,tue,wed,thu

Is there any way to do this and store it in a string.

Thanks in Advance.

3 Answers 3

2

Here is a working code sample for your problem. If you want you can remove comma from last using removeEnd(',')

string test =',mon,,tue,wed,,,thu,';
List<string> testList = test.split(',');
string newString = '';
for(String str : testList)
    if(str.getChars().size() >0)
        newString =newString+str+',';
system.debug('newString+'+newString);

In the new string you will get

mon,tue,wed,thu,

you can remove last comma from removeEnd method(If you don't want it).

0
2

This regex will match the commas at the end of your string and you can use it to replace them with empty string ""

This regex will look for 2 or more commas somewhere in your string except at the beginning and the end. You can use this regex to replace multiple commas with a single one ","

Let me know if this helped.

2

While the accepted answer is valid, I think it is much cleaner to use String.isNotBlank and String.join:

public static String cleanCommaJoin(String input)
{
    List<String> notBlankEntries = new List<String>();
    for (String entry : input.split(','))
        if (String.isNotBlank(entry)) notBlankEntries.add(entry.trim());
    return String.join(notBlankEntries, ',');
}

String.join is a simple solution to the common trailing delimiter anti-pattern. Because of using String.isNotBlank, it also still works if you had, for instance:

String input =' , mon, , tue, wed, , , thu, ';
String output = cleanCommaJoin(input))
system.assertEquals('mon,tue,wed,thu', output);
1
  • 1+ for awesome answer. Thank you so much Adrian.
    – MIX DML
    Commented Oct 15, 2015 at 17:31

You must log in to answer this question.

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