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

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


当前回答

如果您想将整个字符串转换为连接的ASCII值,那么您可以使用这个-

    String str = "abc";  // or anything else

    StringBuilder sb = new StringBuilder();
    for (char c : str.toCharArray())
    sb.append((int)c);

    BigInteger mInt = new BigInteger(sb.toString());
    System.out.println(mInt);

其中你将得到979899作为输出。

这要归功于它。

我只是把它复制在这里,这样其他人就方便了。

其他回答

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

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

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

非常简单。只需将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.

只是不同的方法

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

字节[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()));