我有字符串名称= "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
其他回答
使用Java 9 => String.chars()
String input = "stackoverflow";
System.out.println(input.chars().boxed().collect(Collectors.toList()));
输出- [115,116,97,99,107,111,118,101,114,102,108,111,119]
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);
为此,我们可以直接使用String类
input.codePointAt(index);
我想再给出一个建议,以获得整个字符串转换为相应的ascii码,使用java 8 例如:“abcde”~“979899100101”。
String input = "abcde";
System.out.println(
input.codePoints()
.mapToObj((t) -> "" + t)
.collect(joining()));
将char型转换为int型。
String name = "admin";
int ascii = name.toCharArray()[0];
另外:
int ascii = name.charAt(0);
而不是这样:
String char = name.substring(0,1); //char="a"
您应该使用charAt()方法。
char c = name.charAt(0); // c='a'
int ascii = (int)c;