12

How to convert below String into List<String> in Apex Programming ?

String alpha = 'A, B, C, D';

In java, its very easy like below:

List<String> result = Arrays.asList(alpha.split("\\s*,\\s*"));
1
  • 1
    you can use split(' , '). alpha.split(' , ');
    – Safiya PV
    Commented Apr 24, 2017 at 5:43

2 Answers 2

30

Salesforce provide String class which can be used to work with string. In your case you can use Split method

String alpha = 'A, B, C, D';

List<String> lstAlpha = alpha.split(',');

System.debug(lstAlpha);
1
  • Just a note if you are using the pipe "|" as a delimiter the split function does weird things e.g: String alpha = 'split | this | sentence'; List<String> lstAlpha = alpha.split('|');
    – Nebula
    Commented Dec 5, 2018 at 8:06
5

@Nebula - because pipe (|) is a regex symbol, using following code splits the string properly

String alpha = 'split | this | sentence'; 
List<String> lstAlpha = alpha.split('\\|');

You must log in to answer this question.

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