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

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


当前回答

只是不同的方法

    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
}
public class Ascii {
    public static void main(String [] args){
        String a=args[0];
        char [] z=a.toCharArray();
        for(int i=0;i<z.length;i++){ 
            System.out.println((int)z[i]);
        }
    }
}

而不是这样:

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

您应该使用charAt()方法。

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

不使用额外int变量的一行解决方案:

String name = "admin";
System.out.println((int)name.charAt(0));
String str = "abc";  // or anything else

// Stores strings of integer representations in sequence
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
    sb.append((int)c);

 // store ascii integer string array in large integer
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);