2

How can I get the next alphabetical character in alphabetical sequence? ex. I have 'A' letter, I want 'B' by using 'A'.

2
  • 1
    Using a Map : Map<String, String> m = new Map<String, String>{'A' =>'B', 'B'=> 'C', ...};
    – SF_user
    Commented Jan 11, 2017 at 15:20
  • 2
    What do you want to happen for 'Z' and 'z'?
    – Keith C
    Commented Jan 11, 2017 at 15:31

3 Answers 3

2

You can use String.indexOfChar to find the next value in a simple string. Here's an example:

public static String getNextChar(String oldChar) {
    String key = 'ABCDEFGHIJKLMNOPQRSTUVWXYZAabcdefghijklmnopqrstuvwxyza';
    Integer index = key.indexOfChar(oldChar.charAt(0));
    return index == -1? null: key.substring(index+1, index+2);
}

This includes automatic wraparound from Z -> A and z -> a.

0
8

The methods you'll want to use are listed in the Apex Developer Guide under String Class, specifically charAt and fromCharArray.

Integer charCode = 'A'.charAt(0);
List<Integer> chars = new List<Integer>{charCode+1};
String nextChar = String.fromCharArray(chars);
System.assertEquals('B', nextChar);
1
  • your ans is also correct, but in case of 'Z' letter '[' comes as a next char.
    – Shilpa
    Commented Jan 12, 2017 at 6:15
2

Try using the ASCII values (see http://www.asciitable.com/). In this example, A is 65 and B is 66. A simple numeric increment will get you to the next value. To convert the numeric value back to a character, you can use

String myChar = String.fromCharArray( new List<integer> { 65 } );

where the number is the ASCII value of the letter you need.

2
  • and this should cover the lower case variants (a=97, b=98 etc)
    – Rob Cowell
    Commented Jan 11, 2017 at 15:53
  • Ok, the answer by @frontendloader is better than mine...use that one :-)
    – Rob Cowell
    Commented Jan 11, 2017 at 15:59

You must log in to answer this question.

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