10

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
    Apr 24 '17 at 5:43
22

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
    Dec 5 '18 at 8:06
2

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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