我有字符串名称= "admin"; 然后我做String charValue = name.substring(0,1);/ / charValue = " "
我想将charValue转换为它的ASCII值(97),我如何在java中做到这一点?
我有字符串名称= "admin"; 然后我做String charValue = name.substring(0,1);/ / charValue = " "
我想将charValue转换为它的ASCII值(97),我如何在java中做到这一点?
当前回答
我尝试同样的事情,但最好和最简单的解决方案是使用charAt和访问索引,我们应该创建一个[128]大小的整数数组。
String name = "admin";
int ascii = name.charAt(0);
int[] letters = new int[128]; //this will allocate space with 128byte size.
letters[ascii]++; //increments the value of 97 to 1;
System.out.println("Output:" + ascii); //Outputs 97
System.out.println("Output:" + letters[ascii]); //Outputs 1 if you debug you'll see 97th index value will be 1.
如果你想显示完整字符串的ascii值,你需要这样做。
String name = "admin";
char[] val = name.toCharArray();
for(char b: val) {
int c = b;
System.out.println("Ascii value of " + b + " is: " + c);
}
在这种情况下,你的输出将是: a的Ascii值为:97 d的Ascii值为:100 m的Ascii值为:109 i的Ascii值为:105 n的Ascii值是:110
其他回答
这很简单,获取你想要的字符,并将其转换为int。
String name = "admin";
int ascii = name.charAt(0);
非常简单。只需将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 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]);
}
}
}
只需将char类型转换为int类型。
char character = 'a';
int number = (int) character;
number的值为97。
最简单的方法是:
对于整个字符串转换成ASCII:
public class ConvertToAscii{
public static void main(String args[]){
String abc = "admin";
int []arr = new int[abc.length()];
System.out.println("THe asscii value of each character is: ");
for(int i=0;i<arr.length;i++){
arr[i] = abc.charAt(i); // assign the integer value of character i.e ascii
System.out.print(" "+arr[i]);
}
}
}
输出结果为:
每个字符的asscii值为: 97 100 109 105 110 这里,abc.charAt(i)给出了String数组的单个字符: 当我们将每个字符赋值为整型时,编译器会进行类型转换,
arr[i] = (int) character //这里,每个单独的字符都是ascii值
但是,对于单个字符:
字符串名称= admin; asciiValue = (int) name.charAt(0);//字符'a' System.out.println (asciiValue);