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

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


当前回答

只是不同的方法

    String s = "admin";
    byte[] bytes = s.getBytes("US-ASCII");

字节[0]将表示一个..也就是整个数组中的其他字符。

其他回答

只是不同的方法

    String s = "admin";
    byte[] bytes = s.getBytes("US-ASCII");

字节[0]将表示一个..也就是整个数组中的其他字符。

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

    input.codePointAt(index);

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

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

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

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

number的值为97。

非常简单。只需将char类型转换为int类型。

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

在本例中,您需要首先从String中获取特定的字符,然后强制转换它。

char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.

虽然没有明确要求强制转换,但它提高了可读性。

int ascii = character; // Even this will do the trick.

使用Java 9 => String.chars()

String input = "stackoverflow";
System.out.println(input.chars().boxed().collect(Collectors.toList()));

输出- [115,116,97,99,107,111,118,101,114,102,108,111,119]