我有字符串名称= "admin"; 然后我做String charValue = name.substring(0,1);/ / charValue = " "

我想将charValue转换为它的ASCII值(97),我如何在java中做到这一点?


当前回答

最简单的方法是:

对于整个字符串转换成ASCII:


public class ConvertToAscii{
    public static void main(String args[]){
      String abc = "admin";
      int []arr = new int[abc.length()];
      System.out.println("THe asscii value of each character is: ");
      for(int i=0;i<arr.length;i++){
          arr[i] = abc.charAt(i); // assign the integer value of character i.e ascii
          System.out.print(" "+arr[i]);
      }
    }
}

输出结果为:

每个字符的asscii值为: 97 100 109 105 110 这里,abc.charAt(i)给出了String数组的单个字符: 当我们将每个字符赋值为整型时,编译器会进行类型转换,

arr[i] = (int) character //这里,每个单独的字符都是ascii值

但是,对于单个字符:

字符串名称= admin; asciiValue = (int) name.charAt(0);//字符'a' System.out.println (asciiValue);

其他回答

非常简单。只需将char类型转换为int类型。

char character = 'a';    
int ascii = (int) character;

在本例中,您需要首先从String中获取特定的字符,然后强制转换它。

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.

如果你想要一个字符串中所有字符的ASCII值。你可以用这个:

String a ="asdasd";
int count =0;
for(int i : a.toCharArray())
    count+=i;

如果你想要字符串中单个字符的ASCII码,你可以使用:

(int)a.charAt(index);

或者你可以使用流API为一个字符或从Java 1.8开始的字符串:

public class ASCIIConversion {
    public static void main(String[] args) {
        String text = "adskjfhqewrilfgherqifvehwqfjklsdbnf";
        text.chars()
                .forEach(System.out::println);
    }
}

正如@Raedwald指出的那样,Java的Unicode并不能满足所有字符获取ASCII值的需求。正确的方法(Java 1.7+)如下:

byte[] asciiBytes = "MyAscii".getBytes(StandardCharsets.US_ASCII);
String asciiString = new String(asciiBytes);
//asciiString = Arrays.toString(asciiBytes)

将char型转换为int型。

    String name = "admin";
    int ascii = name.toCharArray()[0];

另外:

int ascii = name.charAt(0);