7

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.

12

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, ''));
| improve this answer | |
2

You can cast a String into an array of Integers, which then gives you the character codes to manipulate. The following reverses a string of chars, "banana" -> "ananab", by using this technique.

String b = 'banana';

// char array, contains the integer representation of a char
List<Integer> rb = new List<Integer>(); 

for (Integer i = b.length() - 1; i > 0; i--) {
  rb.add(b.charAt(i));
}

System.debug(String.fromCharArray(rb));
// prints "ananab"
| improve this answer | |
  • What does this answer have to do with the original question? – Adrian Larson Oct 25 '16 at 21:22
  • 1
    The original question "simple method to get the array of characters", I wrote a simple method to manipulate an Apex string one char at a time. – Arpi Jakab Oct 25 '16 at 22:27

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.