【发布时间】:2011-10-10 01:44:18
【问题描述】:
在我的代码中,我有一个长度为 1 的字符串, 我想将其转换为与(扩展)ASCII码(0-255)的字符值关联的int。
例如:
"A"->65
"f"->102
【问题讨论】:
在我的代码中,我有一个长度为 1 的字符串, 我想将其转换为与(扩展)ASCII码(0-255)的字符值关联的int。
例如:
"A"->65
"f"->102
【问题讨论】:
int asciiCode = (int)A.charAt(0);
或者,如果您确实需要获取字符串文字“A”的ASCII码,而不是变量A引用的字符串:
int asciiCode = (int)"A".charAt(0);
【讨论】:
(int) 'A' 你的第二个更简单。顺便说一句,我认为“我有一个字符串”是一个错字。或许 Belgi 的意思是“我有一根弦”。
"A".charAt(0)和'A'之间没有区别。
charAt() 将其转换为 char 原语,而不是假设您的字符串输入突然是 char 类型因为这就是你所需要的。
11给出,还是说return 10 + 1?当然,相等运算符== 表示它们相等,因此答案必须相同。
你的意思是char?您真正需要做的就是将字符转换为 int。
String a = "A";
int c = (int) a.charAt(0);
System.out.println(c);
输出65
这里有一个更全面的代码。
import java.io.*;
import java.lang.*;
public class scrap{
public static void main(String args[]) throws IOException{
BufferedReader buff =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the char:");
String str = buff.readLine();
for ( int i = 0; i < str.length(); ++i ){
char c = str.charAt(i);
int j = (int) c;
System.out.println("ASCII OF "+c +" = " + j + ".");
}
}
}
【讨论】: