将char值增加1

时间:2014-03-22 07:28:26

标签: java android eclipse string

我有一个带有EditText的应用和一个名为&#34的按钮;转发"。我想要的只是当我输入" a"在EditText中单击按钮,单词" b"输入EditText," c"如果再次按下等等。我试过了:

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

但那当然会打印出首字母后跟数字" 1"。有任何想法吗?非常感谢

6 个答案:

答案 0 :(得分:23)

经过测试并正常工作

所有字母都可以用ASCII值表示。

如果您将字母转换为int,添加1,然后转回char,则字母将增加1个ASCII值(下一个字母)。

例如:

'a'97
'b'98

因此,如果输入为'a'并且您将其输入int,则会得到97。然后添加1并获取98,然后再将其再次转回char并获取'b'

以下是投射示例:

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

所以,你的最终代码可能就是这样:

// 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

当然,只有当一个字符作为输入时,这才能正常工作。

答案 1 :(得分:9)

更简单的方法是:

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

这里value + 1添加字符的十进制等值并将其递增一..这是一个小图表:

enter image description here enter image description here

'z'之后会发生什么? ......它不会崩溃.. see here for the full chart.

答案 2 :(得分:6)

试试这个

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();
}

答案 3 :(得分:3)

您需要将文本值(字符)转换为ascii值,然后将其增加,而不仅仅是文本。

value = edt.getText().toString();
int ascii = (int)value;
edt.setText(Character.toString ((char) ascii+1));

答案 4 :(得分:3)

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

如果以上是您的代码,那么您正在做的是将1连接到value字符串的末尾。因此,单击一下按钮就会改变显示文本的文字"你的文字"到"你的text1"。此过程将在下一次按钮单击时继续显示"您的text11"。问题实际上是类型错误。

答案 5 :(得分:3)

试试这个:

edt.setText(Character.toString((char)(edt.getText().charAt(0) + 1)));
相关问题