Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increase a char value by one

Tags:

I have an app with an EditText and a button named "forward". All I want is just when I type "a" in the EditText and click the button, the word "b" to be typed in the EditText, "c" if pressed again and so on. I have tried:

value = edt.getText();
edt.setText(value + 1);

But that of course will print the initial string followed by the number "1". Any ideas? Thanks a lot

like image 518
Giannis Thanasiou Avatar asked Mar 22 '14 07:03

Giannis Thanasiou


People also ask

Can you increment a char in C?

Because your compiler defaults char to signed char . So the range of values for it is -128 to 127, and incrementing 127 is triggering wraparound. If you want to avoid this, be explicit, and declare your variable as unsigned char .

What does char ++ do in C?

Software Engineering C C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.


2 Answers

Tested and works

All letters can be represented by their ASCII values.

If you cast the letters to an int, add 1, and then cast back to a char, the letter will increase by 1 ASCII value (the next letter).

For example:

'a' is 97
'b' is 98

So if the input was 'a' and you casted that to an int, you would get 97. Then add 1 and get 98, and then finally cast it back to a char again and get 'b'.

Here is an example of casting:

System.out.println( (int)('a') ); // 97
System.out.println( (int)('b') ); // 98
System.out.println( (char)(97) ); // a
System.out.println( (char)(98) ); // b

So, your final code might be this:

// get first char in the input string
char value = et.getText().toString().charAt(0);

int nextValue = (int)value + 1; // find the int value plus 1

char c = (char)nextValue; // convert that to back to a char

et.setText( String.valueOf(c) ); // print the char as a string

Of course this will only work properly if there is one single character as an input.

like image 186
Michael Yaworski Avatar answered Oct 24 '22 05:10

Michael Yaworski


A simpler way would be:

char value = edt.getText().toString().charAt(0);
edt.setText(Character.toString ((char) value+1));

Here the value + 1 adds the decimal equivalent of the character and increments it by one.. Here is a small chart:

enter image description hereenter image description here

Whats happens after 'z'? ... it wont crash.. see here for the full chart..

like image 34
amalBit Avatar answered Oct 24 '22 07:10

amalBit