Apex - Convert comma-separated String to a List

  • 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*"));
    

    you can use split(' , '). alpha.split(' , ');

  • Himanshu

    Himanshu Correct answer

    4 years ago

    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);
    

    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 lstAlpha = alpha.split('|');

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM

Tags used