我有字符串名称= "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
    }
}

}

其他回答

或者你可以使用流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);

只是不同的方法

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

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

几个旨在说明如何做到这一点的答案都是错误的,因为Java字符不是ASCII字符。Java使用Unicode字符的多字节编码。Unicode字符集是ASCII的超集。因此,Java字符串中可能存在不属于ASCII的字符。这样的字符没有ASCII数字值,因此询问如何获得Java字符的ASCII数字值是无法回答的。

但你为什么要这么做?你要怎么处理这个值呢?

如果你想要数值,这样你就可以将Java字符串转换为ASCII字符串,真正的问题是“我如何将Java字符串编码为ASCII”。为此,使用StandardCharsets.US_ASCII对象。

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

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

number的值为97。