我需要计算文本文档中控制字符的数量。
答案 0 :(得分:0)
通过char循环输入char,并将字符的序号与ASCII标准中定义的control characters进行比较。如果你有匹配,请增加你的计数器。
修改强>
String input = "325\nfefe\rw2";
int normalCount = 0;
int controlCount = 0;
for (int i = 0; i < input.length(); ++i) {
int characterCode = (int)input.charAt(i);
if (characterCode == 10 || characterCode == 13) { // Match \n and \r
++controlCount;
}
else {
++normalCount;
}
}
System.out.println("The input contains:");
System.out.println("\t" + normalCount + " printable characters");
System.out.println("\t" + controlCount + " control characters");
会给你这个输出:
The input contains:
9 printable characters
2 control characters