I have a capital letter defined in a variable string, and I want to output the next and previous letters in the alphabet. For example, if the variable was equal to \'C\'>
If you are limited to the latin alphabet, you can use the fact that the characters in the ASCII table are ordered alphabetically, so:
System.out.println((char) ('C' + 1));
System.out.println((char) ('C' - 1));
outputs D
and B
.
What you do is add a char
and an int
, thus effectively adding the int
to the ascii code of the char
. When you cast back to char
, the ascii code is converted to a character.