-3

I need to count the number of control characters from a text document.

AAAAAAAAAAAA
  • 37
  • 1
  • 2
  • 8

2 Answers2

0

Loop through your input char by char and compare the character's ordinal number with the control characters defined in ASCII standard. If you have a match, increase your counter.


Edit:

  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");

Will give you this output:

The input contains:
    9 printable characters
    2 control characters
user1438038
  • 5,821
  • 6
  • 60
  • 94
  • It seems that the major problem is that when I use s.length() (s is a String), it will only give me the number of normal characters (a,b,c...) in the String. – AAAAAAAAAAAA Mar 05 '15 at 19:48
  • That is not true. ``length()`` will also count control characters. The documentation states "*Returns the length of this string. The length is equal to the number of Unicode code units in the string.*" I edited my answer above, where I'm matching line feeds and carriage returns only, but you can process other control characters alike. – user1438038 Mar 06 '15 at 08:05
0

Maybe you can find the isISOControl method from the Character class useful. It returns true is the character is a control character.

Supposing temp is a String and counter is an int where you want to have the total of control characters in the string, someting like this might do the trick:

   for (int i=0,counter=0;i<temp.length();i++) {
        if (!Character.isISOControl(temp.charAt(i))) {
            counter++;
        }
    }
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/33706971) – biasedbit Jan 30 '23 at 02:33