[英]Holding ASCII values 32-126 as an object or through a for loop in Java
I'm trying to have all the ASCII characters from 32-126 held as an object in java. 我正在尝试将32-126中的所有ASCII字符保存为java中的对象。 Is there a way to hold them through a for loop in Java instead of writing all of them out?
有没有办法通过Java中的for循环来保持它们,而不是将它们全部写出来?
ex. 恩。 String characters = "abcdefg";
字符串字符=“ abcdefg”; etc.
等等
Remember that chars are just small integers, so you can use a char
as an index variable in a loop. 请记住,char只是小整数,因此您可以在循环中将
char
用作索引变量。 There are several possible ways to go about this. 有几种方法可以解决此问题。
Here's one that gives a char[]
result: 这是给出
char[]
结果的代码:
char[] carr = new char[95]; // 95 = 126-32+1
for(char ch = 32; ch <= 126; ++ch)
carr[ch-32] = ch;
// for a `String` result, add the following line:
String printableAscii = new String(carr);
Here's another way, that ends up with a String
result: 这是另一种方法,最终得到一个
String
结果:
StringBuilder sb = new StringBuilder();
for (char ch = 32; ch <= 126; ++ch)
sb.append(ch);
String printableAscii = sb.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.