Anonymous
Anonymous

Reputation: 55

How to count whitespace in line? [JAVA]

If I have this code for counting specific word in a file and I want to count the whitespace in line, how can i write it?

Ex. I want to count whitespace in "int a = 0;"

output: whitespace are 3.

Thank you very much.

My code:

public static  void main(String[] args) throws IOException {
    Scanner in = new Scanner (new File("/Users/BooMMacbookProRetina/Desktop/C/Resource [Java Sample file]/GradeCal.java"));

    int c1 = 0, c2 = 0, c3 = 0;

    String t1 = "int";
    String t2 = " ";
    String t3 = ";";

    while (in.hasNext()){
        String line = in.nextLine();
        line = line.trim();
        if (line.length() >0 ){

            int k = -1;
            while (true){   //Count System
                k = line.indexOf(t1, k+1);
                if (k<0) break;
                c1++;
            }
        }
    }
    System.out.println("Total number integers are: " +c1);
    System.out.println("Total number of whitespace in int line are: " +c2);

}

Resource file for counting: Download from my dropbox

Upvotes: 0

Views: 2631

Answers (1)

Karthick Radhakrishnan
Karthick Radhakrishnan

Reputation: 1161

Try this

int a = str.length() - str.replaceAll(" ", "").length();

for your requirement

int whitespaceCount = 0;

//inside while loop
if (Character.isWhitespace(text.charAt(i)) {
        whitespaceCount++
    }

Upvotes: 3

Related Questions