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

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


当前回答

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
}

其他回答

一个简单的方法是:

    int character = 'a';

如果你输入“character”,你得到97。

而不是这样:

String char = name.substring(0,1); //char="a"

您应该使用charAt()方法。

char c = name.charAt(0); // c='a'
int ascii = (int)c;

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

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

下面是代码,从类开始

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
    }
}

}

只是不同的方法

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

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