简体   繁体   English

arraylist split("whitespace") 并计算单词数

[英]arraylist split("whitespace") and count the number of words

so I want to count the number of words in my ArrayList , currently I read lines from a file and saved those lines to the ArrayList .所以我想计算我的ArrayList的单词数,目前我从文件中读取行并将这些行保存到ArrayList
The file has该文件有

word    definition
a       alpha
b       bravo
c       charlie
d       delta
e       echo
f       foxtrot

so when I do arraylist.size() it prints 7. but I want to count the number of words.所以当我做 arraylist.size() 它打印 7. 但我想计算单词的数量。

my code:我的代码:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class WarmUp {
    public static void main(String[] args) {
        BufferedReader br = null;
        String line = null;
        ArrayList<String> elements = new ArrayList<String>();

        try {
            br = new BufferedReader(new FileReader("src/dictionary.txt"));
            while((line=br.readLine()) != null) {
                elements.add(line);
            }
        }
        catch(IOException e) {
            e.printStackTrace();
        }       
    }
}

I think I can use split method so I thought this is the way我想我可以使用 split 方法所以我认为这是方法

ArrayList<String> moreElements = new ArrayList<String>();

for(int i=0; i < elements.size(); i++) {
    String e = elements.get(i);
    moreElements.addAll(e.split(" "));

}

then call moreElements.size() but I'm doing something wrong...然后调用moreElements.size()但我做错了什么......

The method addAll() expects a list but split() returns an array.方法addAll()需要一个列表,但split()返回一个数组。
You must use Arrays.asList() to convert the array to a list.您必须使用Arrays.asList()将数组转换为列表。
Also you must split by multiple spaces.此外,您必须按多个空格分隔。
Change to this:改成这样:

moreElements.addAll(Arrays.asList(e.split("\\s+")));

If you use Java 8 or higher you can use (assuming your List is called elements ):如果您使用 Java 8 或更高版本,则可以使用(假设您的 List 称为elements ):

int count = elements.stream().mapToInt(x -> x.split("\\s+").length).sum();

Solution with a loop:用循环解决:

int count = 0;
for(String line : elements) {
  String[] tmp = line.split("\\s+"); //split on one or more spaces
  count += tmp.length;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM