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

前端 未结 5 635
别跟我提以往
别跟我提以往 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:07

    All the answers are correct but none seem to give a full explanation so I'll try. Just like any other type, a char is stored as a number (16-bit in Java). Unlike other non-numeric types, the mapping of the values of the stored numbers to the values of the chars they represent are well known. This mapping is called the ASCII Table. The Java compiler treats chars as a 16-bit number and therefore you can do the following:

    System.out.print((int)'A'); // prints 65
    System.out.print((char)65); // prints A
    

    For this reason, the ++, -- and other mathematical operations apply to chars and provide a way to increment\decrement their values.

    Note that the casting is cyclic when you exceed 16-bit:

    System.out.print((char)65601); // also prints A
    System.out.print((char)-65471); // also prints A
    

    P.S. This also applies to Kotlin:

    println('A'.toInt()) // prints 65
    println(65.toChar()) // prints A
    println(65601.toChar()) // prints A
    println((-65471).toChar()) // prints A
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-04 04:23

    Well if you mean the 'ABC' then they split into two sequences a-z and A-Z, the simplest way I think would be to use a char variable and to increment the index by one.

    char letter='c';
    letter++;  // (letter=='d')
    

    same goes for decrement:

    char letter='c';
    letter--; // (letter=='b')
    

    thing is that the representation of the letters a-z are 97-122 and A-Z are 65-90, so if the case of the letter is important you need to pay attention to it.

    0 讨论(0)
  • 2021-02-04 04:25

    One way:

    String value = "C";
    int charValue = value.charAt(0);
    String next = String.valueOf( (char) (charValue + 1));
    System.out.println(next);
    
    0 讨论(0)
  • 2021-02-04 04:27

    just like this :

    System.out.printf("%c\n",letter);
    letter++;
    
    0 讨论(0)
提交回复
热议问题