-->

How do I increment a variable to the next or previ

2019-03-12 21:16发布

问题:

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', I would want to output 'B' and 'D'.

回答1:

One way:

String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);


回答2:

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.



回答3:

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.



回答4:

just like this :

System.out.printf("%c\n",letter);
letter++;


回答5:

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