我使用以下代码来计算 Java 中的空行数,但此代码返回的空行数量比实际数量多。
int countEmptyLines(String s) {
int result=0;
Pattern regex = Pattern.compile("(?m)^\\s*$");
Matcher testMatcher = regex.matcher(s);
while (testMatcher.find())
{
result++;
}
return result;}
我做错了什么或者有更好的方法吗?
最佳答案
试试这个:
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:计算文本文件/字符串中的空行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4680588/