I had an unusual request from one of the developers in my team today, so I thought I’d share the solution up here for anyone else who either finds it useful, or has a better approach?
Challenge
If I have a variable which contains a letter, how do I get the next letter in the Alphabet programatically?
Solution
Frustratingly, unlike many other languages such as a PHP/Java/.NET, there is no simple way to do this in Apex. So I created a simple class that should do the trick and thought that I’d share it here in case it’s useful.
If you need more character-based routines, there is a similar but more extensive character class available on the Apex-Lang project on Google Code.
Hopefully they’ll add more of these basic utility classes to the platform eventually.
global class Character {
private static final Integer LOWER_ALPHA_INDEX = 65;
private static final Integer UPPER_ALPHA_INDEX = 90;
public static final Map charToAscii { get; private set; }
public static final Map asciiToChar { get; private set; }
static {
charToAscii = new Map();
charToAscii.put('A', 65);
charToAscii.put('B', 66);
charToAscii.put('C', 67);
charToAscii.put('D', 68);
charToAscii.put('E', 69);
charToAscii.put('F', 70);
charToAscii.put('G', 71);
charToAscii.put('H', 72);
charToAscii.put('I', 73);
charToAscii.put('J', 74);
charToAscii.put('K', 75);
charToAscii.put('L', 76);
charToAscii.put('M', 77);
charToAscii.put('N', 78);
charToAscii.put('O', 79);
charToAscii.put('P', 80);
charToAscii.put('Q', 81);
charToAscii.put('R', 82);
charToAscii.put('S', 83);
charToAscii.put('T', 84);
charToAscii.put('U', 85);
charToAscii.put('V', 86);
charToAscii.put('W', 87);
charToAscii.put('X', 88);
charToAscii.put('Y', 89);
charToAscii.put('Z', 90);
asciiToChar = new Map();
for(String key : charToAscii.keySet()){
asciiToChar.put(charToAscii.get(key), key);
}
}
public static String getNextLetterInAlphabet(String currentLetter) {
// Find the current index by character
Integer currentIndex = charToAscii.get(currentLetter);
// Ensure Z index gets reset to A
Integer newIndex = (currentIndex == UPPER_ALPHA_INDEX) ? LOWER_ALPHA_INDEX : currentIndex + 1;
// Get the next letter by index
String nextLetter = asciiToChar.get(newIndex);
System.debug('If current letter is ' + currentLetter + ', then next letter is: ' + nextLetter);
return nextLetter;
}
}