java 取字符的ascii_如何用java获得字符串的ASCII值
时间: 2024-01-27 14:03:12 浏览: 45
您可以使用Java中的`charAt()`和`(int)`方法来获取字符串中每个字符的ASCII值。
例如,以下代码将打印字符串`str`中每个字符的ASCII值:
```java
String str = "Hello, world!";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int ascii = (int) c;
System.out.println("ASCII value of " + c + " is " + ascii);
}
```
输出结果如下:
```
ASCII value of H is 72
ASCII value of e is 101
ASCII value of l is 108
ASCII value of l is 108
ASCII value of o is 111
ASCII value of , is 44
ASCII value of is 32
ASCII value of w is 119
ASCII value of o is 111
ASCII value of r is 114
ASCII value of l is 108
ASCII value of d is 100
ASCII value of ! is 33
```
相关问题
java获取字符串的ascii码
你可以使用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
```
java 字符串转ASCII
在Java中,字符串转换为ASCII码的方法有多种。一种常见的方法是使用charAt()函数遍历字符串的每个字符,并使用(char)强制类型转换操作将字符转换为对应的ASCII码。代码示例如下:
```java
public static void main(String[] args) {
String s = "abcdefg";
// 遍历字符串
for (int i = 0; i < s.length(); i++) {
System.out.println((int)s.charAt(i));
}
}
```
另一种方法是使用toCharArray()函数将字符串转换为字符数组,然后使用(int)强制类型转换操作将字符转换为对应的ASCII码。代码示例如下:
```java
public static void main(String[] args){
String s = "新年快乐!";
// 字符串转换为字符数组
char[] chars = s.toCharArray();
System.out.println("汉字 ASCII\n----------------------");
// 输出结果
for (int i = 0; i < chars.length; i++){
System.out.println(chars[i + " " + (int)chars[i]);
}
}
```
以上是两种常见的方法,可以根据具体需求选择使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)