[英]Java 8 BufferedReader lines() method prints different count number
[英]Count number of lines in a string in java - BufferedReader behavior
我正在使用countLines函數來計算字符串中的行數。 它使用StringReader和BufferedReader。 但是我得到的結果與示例中對字符串測試的預期結果不同。 有人可以驗證這種情況,並判斷BufferedReader的行為是否符合預期。
package test;
import java.io.BufferedReader;
import java.io.StringReader;
public class LineCountTest {
private static final String test = "This is a\ntest string\n\n\n";
private static final String test2 = "This is a\ntest string\n\n\n ";
public static void main(String[] args) {
System.out.println("Line count: " + countLines(test));
System.out.println("Line count: " + countLines(test2));
}
private static int countLines(String s) {
try (
StringReader sr = new StringReader(s);
BufferedReader br = new BufferedReader(sr)
) {
int count = 0;
for (String line = br.readLine(); line != null; line = br.readLine()) {
count++;
}
return count;
} catch (Exception e) {
return -1;
}
}
}
我期望在兩種情況下countLines都返回5 ,但第一個字符串返回4 。
背景:實際上,我需要line的值來填充字符串數組,並且期望最后一個元素為空字符串。
編輯:我已經知道
String[] lines = s.split("\n", -1);
int count = lines.length;
給我正確/預期的行數。 我僅出於性能方面的原因以及是否有人可以判斷BufferedReader的行為是否正確而詢問。
檢查此代碼 。
class LineCountTest
{
private static final String test = "This is a\ntest string\n\n\n";
private static final String test2 = "This is a\ntest string\n\n\n ";
public static void main(String[] args) {
System.out.println("Line count: " + countLines(test));
System.out.println("Line count: " + countLines(test2));
}
private static int countLines(String s) {
return (s + " ").split("\r?\n").length;
}
}
這樣可以解決您的問題。
此代碼用\\r\\n
或\\n
分割字符串,並返回行數。
添加了額外的空格,以便即使最后一行為空也要計數。
BufferedReader
的行為正確。
條件line != null
導致了問題。
在字符串test
,最后一個\\n
之后沒有任何內容 , BufferedReader#readLine()
其讀取為null
,這就是循環終止且輸出為4
。
在字符串test2
,最后一個\\n
后有一個空格 ,它允許進行另一次迭代,並且輸出為5
。
因此,您發現最后一行以\\n
結束或為非空時可以識別。
為了您的目的,您可以使用:
String[] lines = "This is a\ntest string\n\n\n".split("\r?\n", 5);
這樣可以確保數組具有5個元素。 雖然正則表達式的拆分要慢一些。
如果您在第一個字符串中添加了額外的空格。
private static final String test = "This is a\ntest string\n\n\n ";
您將獲得兩個相同的計數。 主要原因是在for循環中:
for (String line = br.readLine(); line != null; line = br.readLine())
{
count++;
}
for循環的第三個參數“ line = br.readLine()”僅在“ \\ n”之后還有其他可用字符串時才返回字符串。 在第一個字符串中沒有其他字符,但是在第二個字符串中添加了一個空格,該空格現在視為新字符串。 這就是為什么您得到4和5計數數字的原因。
如果您使用Java 8,則:
long lines = stringWithNewlines.chars().filter(x -> x == '\n').count() + 1;
(如果字符串被修剪,最后+1是計算最后一行)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.