如何统计空白? [JAVA]

时间:2016-01-16 16:31:48

标签: java

如果我有这个代码用于计算文件中的特定单词并且我想计算行中的空白,我该如何编写它?

实施例。我想计算" int a = 0;"

中的空格

输出:空格为3。

非常感谢。

我的代码:

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

}

计数资源文件:Download from my dropbox

1 个答案:

答案 0 :(得分:3)

试试这个

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

满足您的要求

int whitespaceCount = 0;

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