如何用java检测控制字符(例如0x0A(换行))?

时间:2015-03-05 08:48:42

标签: java detection control-characters

我需要计算文本文档中控制字符的数量。

1 个答案:

答案 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