Java 字符串转 ASCII 数值代码示例

本文提供 Java 代码示例,演示如何将字符串转换为 ASCII 数值。可以使用 charAt() 方法获取每个字符,并用 Integer.valueOf() 方法将其转换为 ASCII 值。

public class StringToAscii {
    public static void main(String[] args) {
        String str = 'Hello World!';
        int[] asciiValues = convertToAscii(str);
        
        System.out.println('String: ' + str);
        System.out.print('ASCII values: ');
        for (int value : asciiValues) {
            System.out.print(value + ' ');
        }
    }
    
    public static int[] convertToAscii(String str) {
        int[] asciiValues = new int[str.length()];
        
        for (int i = 0; i < str.length(); i++) {
            asciiValues[i] = (int) str.charAt(i);
        }
        
        return asciiValues;
    }
}

输出结果:

String: Hello World!
ASCII values: 72 101 108 108 111 32 87 111 114 108 100 33

该代码将字符串 'Hello World!' 转换为对应的 ASCII 值并输出。

Java 字符串转 ASCII 数值代码示例

原文地址: https://www.cveoy.top/t/topic/hMRZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录