L. Khanna
L. Khanna

Reputation: 17

How do I exclude white spaces from the count?

I have to keep count of how many letters (characters) are in file "test.txt". I got that down, but it includes the spaces as well, which I don't want to include. Any suggestions on how to do so? Thanks so much.

import java.io.*;
class EnglishAnalysis
{
    public static void main(String[] args)
    {
        try
        {
            FileReader fr = new FileReader("test.txt");
            BufferedReader br = new BufferedReader(fr);
            int count = 0;
            String lineCharacters [];
            String line;
            line = br.readLine();
            while (line != null)
            {
                 lineCharacters = line.split("");
                 for (int i = 0; i < lineCharacters.length; i++)
                 {
                     count ++;
                     line = br.readLine();
                 }
                 System.out.println(count);
             }
             br.close();
        }
        catch (IOException e) {}
    }
}

Upvotes: 0

Views: 2451

Answers (5)

GBlodgett
GBlodgett

Reputation: 12819

Or (Java 8+) you can do this very easily with the lines() and chars() methods:

BufferedReader br = new BufferedReader(fr);
long count = br.lines().flatMapToInt(e -> e.codePoints()).filter(e -> !Character.isWhiteSpace(e)).count();

Which will take a Stream<String> of the lines of the file, flat map them to the chars with String::codePoints, filter out any whitespace, and then count the elements

Upvotes: 2

forpas
forpas

Reputation: 164099

Why don't you just add the number of characters for each line after you have cleaned it from all spaces:

    while (line != null) {
        count += line.replaceAll("\\s+", "").length();
        line = br.readLine();
    }

Upvotes: 1

CryptoFool
CryptoFool

Reputation: 23099

Maybe I'm missing something, but I don't understand what good the split does. I'd do this:

public static void main(String[] args) {
    try {
        FileReader fr = new FileReader("/tmp/test.txt");
        BufferedReader br = new BufferedReader(fr);
        int count = 0;
        String line;
        line = br.readLine();
        while (line != null) {
            for (int i = 0; i < line.length(); i++)
                if (!Character.isWhitespace(line.charAt(i)))
                    count++;
            line = br.readLine();
        }
        br.close();
        System.out.println(count);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

Specifically, I see no need to modify the input at all, by calling split, making extra copies, doing find/replace, etc. That all just takes extra time and space.

And actually, I don't see any reason to bother processing the file in lines:

public static void main(String[] args) {
    try {
        FileReader fr = new FileReader("/tmp/test.txt");
        BufferedReader br = new BufferedReader(fr);
        int count = 0;
        while (true) {
            int c = br.read();
            if (c < 0)
                break;
            if (!Character.isWhitespace(c))
                count++;
        }
        br.close();
        System.out.println(count);
    } catch (IOException ex) {
        System.out.println(ex);
    }
}

Using a BufferedReader in and of itself gives you the efficiency of not reading the file character by character. So you save an extra copy of each line by doing it this way.

Upvotes: 1

SevitomTheOgre
SevitomTheOgre

Reputation: 44

The character class has an "isWhiteSpace()" method

java.lang.Character.isWhitespace(char ch)

while (line != null)
  {
    for (int i = 0; i < line.length(); i++)
    {
      if (!Character.isWhitespace(line.charAt(i)))
         count ++;
      line = br.readLine();
    }
    System.out.println(count);
  }

Upvotes: 0

Anis R.
Anis R.

Reputation: 6912

Why not removing whitespaces from the string, before doing the split and count?

One way of doing it, using regular expressions:

while (line != null)
{
  line.replaceAll("\\s+","");
  lineCharacters = line.split("");
  ...
}

Upvotes: 0

Related Questions