私はString name = "admin";
それから私はするString charValue = name.substring(0,1); //charValue="a"
を ASCII 値 (97) に変換したいのですがcharValue
、Java でこれを行うにはどうすればよいですか?
とてもシンプルです。char
としてキャストするだけint
です。
char character = 'a';
int ascii = (int) character;
あなたの場合、最初に文字列から特定の文字を取得してからキャストする必要があります。
char character = name.charAt(0); // This gives the character 'a'
int ascii = (int) character; // ascii is now 97.
キャストは明示的には必要ありませんが、読みやすさが向上します。
int ascii = character; // Even this will do the trick.
これの代わりに:
String char = name.substring(0,1); //char="a"
charAt()
メソッドを使用する必要があります。
char c = name.charAt(0); // c='a'
int ascii = (int)c;
Java文字はASCII文字ではないため、これを行う方法を示すことを目的としたいくつかの回答はすべて間違っています。Java は、Unicode 文字のマルチバイト エンコーディングを使用します。Unicode 文字セットは、ASCII のスーパー セットです。そのため、ASCII に属さない文字が Java 文字列に含まれる場合があります。そのような文字には ASCII 数値がないため、Java 文字の ASCII 数値を取得する方法を尋ねても答えられません。
しかし、なぜあなたはとにかくこれをやりたいのですか?値をどうするか?
Java 文字列を ASCII 文字列に変換できるように数値が必要な場合、実際の問題は「Java 文字列を ASCII としてエンコードするにはどうすればよいか」です。そのためには、 object を使用しますStandardCharsets.US_ASCII
。
char を int にキャストするだけです。
char character = 'a';
int number = (int) character;
の値はnumber
97 になります。
これはすでにいくつかの形式で回答されていることを知っていますが、ここにすべての文字を調べるための私のコードがあります。
クラスから始まるコードは次のとおりです
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
}
}
}
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 name = "admin";
char[] ch = name.toString().toCharArray(); //it will read and store each character of String and store into char[].
for(int i=0; i<ch.length; i++)
{
System.out.println(ch[i]+
"-->"+
(int)ch[i]); //this will print both character and its value
}
@Raedwald が指摘したように、Java の Unicode は、ASCII 値を取得するためにすべての文字に対応しているわけではありません。正しい方法(Java 1.7+)は次のとおりです。
byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)
このコードで ASCII の番号を確認できます。
String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97
私が間違っている場合は、お詫び申し上げます。