How do I increment a variable to the next or previous letter in the alphabet?

前端 未结 5 637
别跟我提以往
别跟我提以往 2021-02-04 03:48

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\'

5条回答
  •  花落未央
    2021-02-04 04:10

    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.

提交回复
热议问题