0

I would like to split emails by an a comma and put each email into an array. The problem I'm having is that I can't put each email into each index in the string array.

public string additionalEmails {get;set;}
String[] emailTestString = new string[]{};
emailTestString =  additionalEmails.split(',');

I believe the above splits the emails but then stores then all at index 0 (But i could be wrong)

I tried running a for each loop as follows:

        string[] strList = new string[]{};
        Integer i = 0;
        for( String str : emailTestString) 
        {
                strList[i] = str;
                i++;
        }

But it doesn't even enter the for each loop.

So if anyone can help me but each email into an array I would be very grateful.

Input:

enter image description here

Output when I display on screen:

enter image description here

As you can see it doesn't split by the comma.

5
  • List<strList> result = additionalEmails.split(','); <--- What is wrong with this code? Can you post your input?
    – kurunve
    Commented Aug 21, 2017 at 9:58
  • I have updated my post
    – user48107
    Commented Aug 21, 2017 at 10:31
  • so, basically you want to add end of the line character instead of a comma?
    – kurunve
    Commented Aug 21, 2017 at 10:33
  • I would like to have each email in a separate index within a array. I use split() to separate each email as in the input, each email is split up by a comma.
    – user48107
    Commented Aug 21, 2017 at 10:45
  • It is worth pointing out that when you use system.debug() to output a list (and String.split() does return a List<String>), Salesforce does put commas between each value. Since that's so similar to the format that you're using for input, it'd be easy to think that your code wasn't working. Printing the size of the list in a debug statement might help you confirm whether or not your code is working.
    – Derek F
    Commented Aug 21, 2017 at 12:39

1 Answer 1

1

The string split method is the right one to use and it returns an array of the values that lie between the supplied value. (Some values need escaping because of regular expression support but comma doesn't.)

But as this is user input, best to also filter out cases like two commas in a row or white space:

public string additionalEmails {get;set;}

String[] emailTestString = new String[] {};
for (String email : additionalEmails.split(',')) {
    String trimmed = email.trim();
    if (trimmed.length() > 0) emailTestString.add(trimmed);
}

You must log in to answer this question.