stringsalesforceapexsfdc

Creating string from Custom label


I have a custom label in CSV format called Test having value abc, xyz and I want to create a string in the form 'abc','xyz'. How would we do that?

Code Written so far

String str = System.Label.Test; // next steps


Solution

  • The code below splits the label at the comma to create a list. Each string in the list is them trimmed to remove whitespace and added to another list. That list is joined using ',' as the delimiter.

    String str = System.Label.Test; // next steps
    final String SINGLE_QUOTE = '\'';
    final String COMMA = ',';
    final String DELIMITER = SINGLE_QUOTE + COMMA + SINGLE_QUOTE;
    String formattedLabel = SINGLE_QUOTE;
    List<String> stringItems = new List<String>();
    
    for(String item : str.split(',')){
        stringItems.add(item.trim());
    }
    formattedLabel += String.join(stringItems, DELIMITER);
    formmatedLabel += SINGLE_QUOTE;
    System.debug(formattedLabel);