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

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


当前回答

将char型转换为int型。

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

另外:

int ascii = name.charAt(0);

其他回答

正如@Raedwald指出的那样,Java的Unicode并不能满足所有字符获取ASCII值的需求。正确的方法(Java 1.7+)如下:

byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)

将char型转换为int型。

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

另外:

int ascii = name.charAt(0);

或者你可以使用流API为一个字符或从Java 1.8开始的字符串:

public class ASCIIConversion {
    public static void main(String[] args) {
        String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
        text.chars()
                .forEach(System.out::println);
    }
}

这很简单,获取你想要的字符,并将其转换为int。

String name = "admin";
int ascii = name.charAt(0);

你可以用这段代码检查ASCII的数字。

String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97

如果我错了,我道歉。