我有字符串名称= "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 str = "abc"; // or anything else
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray())
sb.append((int)c);
BigInteger mInt = new BigInteger(sb.toString());
System.out.println(mInt);
其中你将得到979899作为输出。
这要归功于它。
我只是把它复制在这里,这样其他人就方便了。
而不是这样:
String char = name.substring(0,1); //char="a"
您应该使用charAt()方法。
char c = name.charAt(0); // c='a'
int ascii = (int)c;
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);
或者你可以使用流API为一个字符或从Java 1.8开始的字符串:
public class ASCIIConversion {
public static void main(String[] args) {
String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
text.chars()
.forEach(System.out::println);
}
}
我知道这个问题已经以几种形式回答了,但这里是我的一点代码,看看所有的字符。
下面是代码,从类开始
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
}
}
}