java字符串转ascll编码
时间: 2024-06-15 12:08:39 浏览: 118
在Java中,可以使用以下方法将字符串转换为ASCII编码:
1. 使用String类的toCharArray()方法将字符串转换为字符数组。
2. 遍历字符数组,使用强制类型转换将每个字符转换为ASCII码。
3. 将ASCII码存储在一个整数数组中。
下面是一个示例代码:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello";
int[] asciiArray = convertToAscii(str);
for (int i = 0; i < asciiArray.length; i++) {
System.out.println("Character: " + str.charAt(i) + ", ASCII: " + asciiArray[i]);
}
}
public static int[] convertToAscii(String str) {
char[] charArray = str.toCharArray();
int[] asciiArray = new int[charArray.length];
for (int i = 0; i < charArray.length; i++) {
asciiArray[i] = (int) charArray[i];
}
return asciiArray;
}
}
```
运行以上代码,输出结果如下:
```
Character: H, ASCII: 72
Character: e, ASCII: 101
Character: l, ASCII: 108
Character: l, ASCII: 108
Character: o, ASCII: 111
```
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)