簡體   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