猿问

将 ASCII 值 32-126 作为对象或通过 Java 中的 for 循环

我试图将 32-126 中的所有 ASCII 字符作为对象保存在 java 中。有没有办法通过 Java 中的 for 循环来保存它们而不是将它们全部写出来?

前任。字符串字符 = "abcdefg"; 等等。


守着一只汪
浏览 280回答 1
1回答

catspeake

请记住,字符只是小整数,因此您可以使用 achar作为循环中的索引变量。有几种可能的方法来解决这个问题。这是一个给出char[]结果的方法:char[] carr = new char[95]; // 95 = 126-32+1for(char ch = 32; ch <= 126; ++ch)&nbsp;&nbsp; &nbsp; carr[ch-32] = ch;// for a `String` result, add the following line:String printableAscii = new String(carr);这是另一种方式,String结果是:StringBuilder sb = new StringBuilder();for (char ch = 32; ch <= 126; ++ch)&nbsp; &nbsp; sb.append(ch);String printableAscii = sb.toString();
随时随地看视频慕课网APP

相关分类

Java
我要回答