In my code I have A string with length 1, I want to convert it to the int associated with the character valu开发者_Python百科e of (extended) ASCII code (0-255).
For example:
"A"->65
"f"->102
int asciiCode = (int)A.charAt(0);
Or, if you really need to get the ascii code for the string literal "A", instead of a string referenced by variable A:
int asciiCode = (int)"A".charAt(0);
You mean char
? All you really need to do is cast the character to an int.
String a = "A";
int c = (int) a.charAt(0);
System.out.println(c);
Outputs 65
Here's a more comprehensive code.
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 + ".");
}
}
}
精彩评论