[SalesForce] Coverting a String to Array of Characters

I would like to ask a simple question but seems to be complex if we talk in context of Apex programming.
Like in java we have a simple method to get the array of characters by using

public char[] toCharArray(): String

Do we have such kind of provision or some kind of custom logic to define not much complex without making use of subString() method in Apex?

EDIT:
I would like to convert a String "banana" such that each of its characters can be manipulated.

Best Answer

It depends what you mean by "such that each of its characters can be manipulated". Apex Strings (as in Java) are immutable, so a true manipulation of the source value is not going to happen. Nor is there a char datatype in Apex. You can inspect individual "chars" by using the String.mid method, or you can efficiently create an array of 1-char long Strings from your source string (similar to a char[]). You could then write new "chars" into elements of that array, and the join/recombine the parts as necessary, to form the desired result in a new String. Example:

// splitting on empty gives you an array of the string's "chars":
String source = 'foo bar';
String[] chars = source.split('');
// the 1st element in an Apex '' split is garbage; remove it:
chars.remove(0);
System.debug(chars);
// change a char:
chars[6] = 'z';
// prints "foo baz":
System.debug(String.join(chars, ''));
Related Topic