为什么我的单词计数器有时会减一?
Why is my word counter sometimes off by one?
大部分时间它都能正常工作。很少会减一。猜猜看?
public static int countWords(File file) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<String> strList = new ArrayList<>();
while ((line=br.readLine())!=null){
String[] strArray= line.split("\s+");
for (int i=0; i<strArray.length;i++){
strList.add(strArray[i]);
}
}
return strList.size();
}
特别是在下面的示例中,它给出了 3 而不是 2:
\n
k
如果您正在使用 Java 8,您可以使用 Streams 并过滤您认为是 "word" 的内容。例如:
List<String> l = Files.lines(Paths.get("files/input.txt")) // Read all lines of your input text
.flatMap(s->Stream.of(s.split("\s+"))) // Split each line by white spaces
.filter(s->s.matches("\w")) // Keep only the "words" (you can change here as you want)
.collect(Collectors.toList()); // Put the stream in a List
在这种特定情况下,它将输出 [k]
。
您当然可以在 Java 7 中执行相同的操作,方法是调整您的代码并在 for
循环中添加此条件:
if(strArray[i].matches("\w"))
strList.add(strArray[i]); // Keep only the "words" - again, use your own criteria
就是比较麻烦
希望对您有所帮助。
我猜第二行被分成了两个字符串,"" 和 "k"。请看下面的代码:
import java.util.Arrays;
public static void main(String[] args) {
String str = " k";
String[] array = str.split("\\s+");
System.out.println("length of array is " + array.length); // length is 2
System.out.println(Arrays.toString(array)); //array is [, k]
}
大部分时间它都能正常工作。很少会减一。猜猜看?
public static int countWords(File file) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
List<String> strList = new ArrayList<>();
while ((line=br.readLine())!=null){
String[] strArray= line.split("\s+");
for (int i=0; i<strArray.length;i++){
strList.add(strArray[i]);
}
}
return strList.size();
}
特别是在下面的示例中,它给出了 3 而不是 2:
\n
k
如果您正在使用 Java 8,您可以使用 Streams 并过滤您认为是 "word" 的内容。例如:
List<String> l = Files.lines(Paths.get("files/input.txt")) // Read all lines of your input text
.flatMap(s->Stream.of(s.split("\s+"))) // Split each line by white spaces
.filter(s->s.matches("\w")) // Keep only the "words" (you can change here as you want)
.collect(Collectors.toList()); // Put the stream in a List
在这种特定情况下,它将输出 [k]
。
您当然可以在 Java 7 中执行相同的操作,方法是调整您的代码并在 for
循环中添加此条件:
if(strArray[i].matches("\w"))
strList.add(strArray[i]); // Keep only the "words" - again, use your own criteria
就是比较麻烦
希望对您有所帮助。
我猜第二行被分成了两个字符串,"" 和 "k"。请看下面的代码:
import java.util.Arrays;
public static void main(String[] args) {
String str = " k";
String[] array = str.split("\\s+");
System.out.println("length of array is " + array.length); // length is 2
System.out.println(Arrays.toString(array)); //array is [, k]
}