如何将 ASCII 码转换为字符
    
    Rupam Yadav
    2023年10月12日
    
    Java
    Java ASCII
    Java Char
    
- 在 Java 中使用强制转换将 ASCII 码转换为 Char 码
- 
          
            在 Java 中使用 Character.toString将 ASCII 码转换为字符
- 
          
            在 Java 中使用 Character.toString转换 ASCII 码为字符
- 
          
            在 Java 中使用 Character.toChars()转换 ASCII 码为字符
 
本文讨论了如何使用 Java 中的方法将一个 ASCII 码转换为字符。此外,我们还演示了如何将大写字母转换成小写字母,反之亦然。
在 Java 中使用强制转换将 ASCII 码转换为 Char 码
从 ASCII 码中提取字符的最基本也是最简单的方法是直接将 ASCII 码强制转换为字符,这将把 int 类型的 asciiValue 转换为 char 类型。
public class Main {
  public static void main(String[] args) {
    int asciiValue = 97;
    char convertedChar = (char) asciiValue;
    System.out.println(convertedChar);
  }
}
输出:
a
在 Java 中使用 Character.toString 将 ASCII 码转换为字符
Java 的字符类为我们提供了一个 toString() 方法,该方法在 codePoint 中转换为一个字符;在本例中,我们有一个 ASCII 码。我们可以把转换方法放入一个循环中,得到所有的大写英文字母。注意,循环从 65 到 90,这就是大写字母对应的 ASCII 码。
这个方法与我们上面使用的例子相比,好处是如果 int 值没有被正确验证,它可以抛出一个异常。
public class Main {
  public static void main(String[] args) {
    int asciiValue = 65;
    for (int i = asciiValue; i <= 90; i++) {
      String convertedChar = Character.toString(i);
      System.out.println(i + " => " + convertedChar);
    }
  }
}
输出:
65 => A
66 => B
67 => C
68 => D
69 => E
70 => F
71 => G
72 => H
73 => I
74 => J
75 => K
76 => L
77 => M
78 => N
79 => O
80 => P
81 => Q
82 => R
83 => S
84 => T
85 => U
86 => V
87 => W
88 => X
89 => Y
90 => Z
在 Java 中使用 Character.toString 转换 ASCII 码为字符
要将 ASCII 码转换为小写字母,我们只需要改变循环范围;它应该以 97 开始,以 122 结束。
public class Main {
  public static void main(String[] args) {
    int asciiValue = 97;
    for (int i = asciiValue; i <= 122; i++) {
      String convertedChar = Character.toString((char) i);
      System.out.println(i + " => " + convertedChar);
    }
  }
}
输出:
97 => a
98 => b
99 => c
100 => d
101 => e
102 => f
103 => g
104 => h
105 => i
106 => j
107 => k
108 => l
109 => m
110 => n
111 => o
112 => p
113 => q
114 => r
115 => s
116 => t
117 => u
118 => v
119 => w
120 => x
121 => y
122 => z
在 Java 中使用 Character.toChars() 转换 ASCII 码为字符
我们可以使用 Java 中字符类的另一个方法,即 toChars;它接收一个类似 ASCII 值的 CodePoint,并返回一个 char 数组。
public class Main {
  public static void main(String[] args) {
    int asciiValue = 255;
    char[] convertedCharArray = Character.toChars(asciiValue);
    System.out.println(convertedCharArray);
  }
}
输出:
ÿ
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Rupam Yadav
    Rupam Saini is an android developer, who also works sometimes as a web developer., He likes to read books and write about various things.
LinkedIn