7

In Apex code how do we convert string to array. Java toCharArray does not work.

String string = 'somestring' to [s, o, m, e ...]

11

You can use the String.split() method, using '' (two single quotes) as a parameter::

String ourString = 'Salesforce SE';
String[] stringCharacters = ourString.split('');
System.debug(stringCharacters);
// stringCharacters is a List<String>, each element being a substring of length 1:
// (,S,a,l,e,s,f,o,r,c,e, ,S,E)

Note that the first element in the collection will be "empty":

String firstElement = stringCharacters.remove(0);
System.debug(stringCharacters);
// (S,a,l,e,s,f,o,r,c,e, ,S,E)
2
  • I just tried this in Salesforce Developer Console and got the following output: (S, a, l, e, s, f, o, r, c, e, ...) for the first debug, and (a, l, e, s, f, o, r, c, e, , ...) for the second debug Mar 28 '20 at 18:00
  • I tried it and it does work. But, can you explain how single quote('') i.e. empty string is splitting every character. I could not understand why it is working.
    – devforce
    Oct 21 '21 at 15:38

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.