我有字符串名称= "admin"; 然后我做String charValue = name.substring(0,1);/ / charValue = " "
我想将charValue转换为它的ASCII值(97),我如何在java中做到这一点?
我有字符串名称= "admin"; 然后我做String charValue = name.substring(0,1);/ / charValue = " "
我想将charValue转换为它的ASCII值(97),我如何在java中做到这一点?
当前回答
你可以用这段代码检查ASCII的数字。
String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97
如果我错了,我道歉。
其他回答
你可以用这段代码检查ASCII的数字。
String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97
如果我错了,我道歉。
将char型转换为int型。
String name = "admin";
int ascii = name.toCharArray()[0];
另外:
int ascii = name.charAt(0);
这很简单,获取你想要的字符,并将其转换为int。
String name = "admin";
int ascii = name.charAt(0);
我尝试同样的事情,但最好和最简单的解决方案是使用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
几个旨在说明如何做到这一点的答案都是错误的,因为Java字符不是ASCII字符。Java使用Unicode字符的多字节编码。Unicode字符集是ASCII的超集。因此,Java字符串中可能存在不属于ASCII的字符。这样的字符没有ASCII数字值,因此询问如何获得Java字符的ASCII数字值是无法回答的。
但你为什么要这么做?你要怎么处理这个值呢?
如果你想要数值,这样你就可以将Java字符串转换为ASCII字符串,真正的问题是“我如何将Java字符串编码为ASCII”。为此,使用StandardCharsets.US_ASCII对象。