Java:计算文本文件/字符串中的空行 [英] Java: Count empty lines in a text file/string

查看:696
本文介绍了Java:计算文本文件/字符串中的空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码来计算Java中的空行,但是这个代码返回的空行数比它大。

  int countEmptyLines(String s){
int result = 0;
模式regex = Pattern.compile((?m)^ \\s * $);
Matcher testMatcher = regex.matcher(s);
while(testMatcher.find())
{
result ++;
}
return result;}

我做错了什么



<$ p

$ p> final BufferedReader br = new BufferedReader(new StringReader(hello\\\
\\\
world\\\
));
String line;
int empty = 0;
while((line = br.readLine())!= null){
if(line.trim()。isEmpty()){
empty ++;
}
}
System.out.println(空);


I am using the following code to count empty lines in Java, but this code returns a greater number of empty lines than there are.

int countEmptyLines(String s) {
int result=0;
Pattern regex = Pattern.compile("(?m)^\\s*$");
Matcher testMatcher = regex.matcher(s);
while (testMatcher.find())
{
  result++;
}
return result;}

What am I doing wrong or is there a better way to do it?

解决方案

Try this:

final BufferedReader br = new BufferedReader(new StringReader("hello\n\nworld\n"));
String line;
int empty = 0;
while ((line = br.readLine()) != null) {
  if (line.trim().isEmpty()) {
    empty++;
  }
}
System.out.println(empty);

这篇关于Java:计算文本文件/字符串中的空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆