java获取字符串的ascii码
时间: 2024-01-25 13:03:11 浏览: 121
你可以使用Java中的`charAt()`方法和`(int)`转换操作符来获取字符串中每个字符的ASCII码。下面是一个示例代码:
```java
public class Main {
public static void main(String[] args) {
String str = "Hello, World!";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int ascii = (int) c;
System.out.println("Character: " + c + ", ASCII: " + ascii);
}
}
}
```
这段代码会遍历字符串中的每个字符,将其转换为ASCII码,并打印出来。输出结果如下:
```
Character: H, ASCII: 72
Character: e, ASCII: 101
Character: l, ASCII: 108
Character: l, ASCII: 108
Character: o, ASCII: 111
Character: ,, ASCII: 44
Character: , ASCII: 32
Character: W, ASCII: 87
Character: o, ASCII: 111
Character: r, ASCII: 114
Character: l, ASCII: 108
Character: d, ASCII: 100
Character: !, ASCII: 33
```
阅读全文