简体   繁体   English

如何将字符串(长度为1)转换为关联的ASCII代码int值(0-255)?

[英]How to convert String (of length 1) to the associated int value of ASCII code (0-255)?

In my code I have A string with length 1, I want to convert it to the int associated with the character value of (extended) ASCII code (0-255). 在我的代码中,我有一个长度为1的字符串,我想将其转换为与(扩展)ASCII代码(0-255)的字符值关联的int。

For example: 例如:

"A"->65
"f"->102
int asciiCode = (int)A.charAt(0);

或者,如果您确实需要获取字符串文字“ A”的ascii代码,而不是变量A引用的字符串:

int asciiCode = (int)"A".charAt(0);

You mean char ? 你是说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 输出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 + ".");
      }
      }

  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM