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

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

提交回复
热议问题