Increase a char value by one

前端 未结 6 2145
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-18 17:24

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\

相关标签:
6条回答
  • 2021-02-18 17:39

    Try this one

    String convertString = getIncrementStr("abc");
    public static String getIncrementStr(String str){
        StringBuilder sb = new StringBuilder();
        for(char c:str.toCharArray()){
            sb.append(++c);
        }
        return sb.toString();
    }
    
    0 讨论(0)
  • 2021-02-18 17:40

    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 here enter image description here

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

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-02-18 17:45

    Try this:

    edt.setText(Character.toString((char)(edt.getText().charAt(0) + 1)));
    
    0 讨论(0)
  • 2021-02-18 18:01
    String value = edt.getText();
    edt.setText(value + 1);
    

    If the above is your code, then what you are doing is concatenating a 1 to the end of your value string. Thus, a button click would alter the displayed text from "your text" to "your text1". This process would continue on the next button click to show "your text11". The issue is really a type error.

    0 讨论(0)
  • 2021-02-18 18:02

    You need to convert the text value (character) to the ascii value, then increase it, not just the text.

    value = edt.getText().toString();
    int ascii = (int)value;
    edt.setText(Character.toString ((char) ascii+1));
    
    0 讨论(0)
提交回复
热议问题