我有字符串名称= "admin"; 然后我做String charValue = name.substring(0,1);/ / charValue = " "

我想将charValue转换为它的ASCII值(97),我如何在java中做到这一点?


当前回答

我知道这个问题已经以几种形式回答了,但这里是我的一点代码,看看所有的字符。

下面是代码,从类开始

public class CheckChValue {  // Class name
public static void main(String[] args) { // class main

    String name = "admin"; // String to check it's value
    int nameLenght = name.length(); // length of the string used for the loop

    for(int i = 0; i < nameLenght ; i++){   // while counting characters if less than the length add one        
        char character = name.charAt(i); // start on the first character
        int ascii = (int) character; //convert the first character
        System.out.println(character+" = "+ ascii); // print the character and it's value in ascii
    }
}

}

其他回答

将char型转换为int型。

    String name = "admin";
    int ascii = name.toCharArray()[0];

另外:

int ascii = name.charAt(0);
String name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].

for(int i=0; i<ch.length; i++)
{
    System.out.println(ch[i]+
                       "-->"+
                       (int)ch[i]); //this will print both character and its value
}

为此,我们可以直接使用String类

    input.codePointAt(index);

我想再给出一个建议,以获得整个字符串转换为相应的ascii码,使用java 8 例如:“abcde”~“979899100101”。

    String input = "abcde";
    System.out.println(
            input.codePoints()
                    .mapToObj((t) -> "" + t)
                    .collect(joining()));

如果你想要一个字符串中所有字符的ASCII值。你可以用这个:

String a ="asdasd";
int count =0;
for(int i : a.toCharArray())
    count+=i;

如果你想要字符串中单个字符的ASCII码,你可以使用:

(int)a.charAt(index);

只需将char类型转换为int类型。

char character = 'a';
int number = (int) character;

number的值为97。