繁体   English   中英

在java中将字符转换为ASCII数值

[英]Convert character to ASCII numeric value in java

我有String name = "admin";
然后我做String charValue = name.substring(0,1); //charValue="a" String charValue = name.substring(0,1); //charValue="a"

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

很简单的。 只需将您的charint

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 s = "admin";
    byte[] bytes = s.getBytes("US-ASCII");

bytes[0]将代表 a.. 的 ascii,从而代表整个数组中的其他字符。

取而代之的是:

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 的超集。 因此,Java 字符串中可能存在不属于 ASCII 的字符。 此类字符没有 ASCII 数值,因此询问如何获取 Java 字符的 ASCII 数值是无解的。

但是你为什么要这样做呢? 你打算用这个值做什么?

如果您需要数值以便将 Java 字符串转换为 ASCII 字符串,那么真正的问题是“如何将 Java 字符串编码为 ASCII”。 为此,请使用对象StandardCharsets.US_ASCII

如果您想将整个字符串转换为连接的 ASCII 值,那么您可以使用这个 -

    String str = "abc";  // or anything else

    StringBuilder sb = new StringBuilder();
    for (char c : str.toCharArray())
    sb.append((int)c);

    BigInteger mInt = new BigInteger(sb.toString());
    System.out.println(mInt);

其中您将获得 979899 作为输出。

归功于

我只是把它复制到这里,以便其他人方便。

将字符转换为整数。

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

还 :

int ascii = name.charAt(0);

只需将字符转换为整数。

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

number的值为 97。

public class Ascii {
    public static void main(String [] args){
        String a=args[0];
        char [] z=a.toCharArray();
        for(int i=0;i<z.length;i++){ 
            System.out.println((int)z[i]);
        }
    }
}

我知道这已经以多种形式得到了回答,但这是我的一些代码,用于查看所有字符。

这是代码,从类开始

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
    }
}

}

一个简单的方法是:

    int character = 'a';

如果你打印“character”,你会得到 97。

很简单,得到你想要的字符,然后转换成int。

String name = "admin";
int ascii = name.charAt(0);
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)

或者您可以将 Stream API 用于 1 个字符或从 Java 1.8 开始的字符串:

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

使用 Java 9 => String.chars()

String input = "stackoverflow";
System.out.println(input.chars().boxed().collect(Collectors.toList()));

输出 - [115, 116, 97, 99, 107, 111, 118, 101, 114, 102, 108, 111, 119]

您可以使用此代码检查 ASCII 的编号。

String name = "admin";
char a1 = a.charAt(0);
int a2 = a1;
System.out.println("The number is : "+a2); // the value is 97

如果我错了,道歉。

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

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

如果你想要字符串中单个字符的 ASCII 你可以去:

(int)a.charAt(index);

我正在尝试同样的事情,但最好和最简单的解决方案是使用 charAt 并访问索引,我们应该创建一个 [128] 大小的整数数组。

String name = "admin"; 
int ascii = name.charAt(0); 
int[] letters = new int[128]; //this will allocate space with 128byte size.
letters[ascii]++; //increments the value of 97 to 1;
System.out.println("Output:" + ascii); //Outputs 97
System.out.println("Output:" +  letters[ascii]); //Outputs 1 if you debug you'll see 97th index value will be 1.

如果要显示完整字符串的 ascii 值,则需要执行此操作。

String name = "admin";
char[] val = name.toCharArray();
for(char b: val) {
 int c = b;
 System.out.println("Ascii value of " + b + " is: " + c);
}

在这种情况下,您的输出将是: a 的 Ascii 值是:97 d 的 Ascii 值是:100 m 的 Ascii 值是:109 i 的 Ascii 值是:105 n 的 Ascii 值是:110

做到这一点的简单方法是:

将整个 String 转换为 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]);
      }
    }
}


输出是:

THe asscii value of each character is: 97 100 109 105 110


这里, abc.charAt(i)给出了 String 数组的单个字符: 当我们将每个字符分配给整数类型时,编译器将类型转换为,

arr[i] = (int) character // Here, every individual character is coverted in ascii value

但是,对于单个字符:

String name = admin; asciiValue = (int) name.charAt(0);// for character 'a' System.out.println(asciiValue);

为此,我们可以立即使用 String 类的

    input.codePointAt(index);

我想再提出一个建议,将整个字符串转换为相应的 ascii 代码,例如使用 java 8,“abcde”到“979899100101”。

    String input = "abcde";
    System.out.println(
            input.codePoints()
                    .mapToObj((t) -> "" + t)
                    .collect(joining()));
char c = 'a';
byte b = (byte) (c & 0x7F);

不使用额外 int 变量的一行解决方案:

String name = "admin";
System.out.println((int)name.charAt(0));

暂无
暂无

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

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