-2

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

4

1 回答 1

0

逐个字符地循环输入字符,并将字符的序号与ASCII 标准中定义的控制字符进行比较。如果你有匹配,增加你的计数器。


编辑:

  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
于 2015-03-05T09:02:15.900 回答