7

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

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

1 Answer 1

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 in API version 34.0 and earlier,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
  • 1
    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 Commented Mar 28, 2020 at 18:00
  • 1
    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
    Commented Oct 21, 2021 at 15:38

You must log in to answer this question.

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