[英]Java: Incrementing wordCount for each word stored into array from file
I'm trying to read a file and store the words from the file into a string array excluding spaces/multiple spaces. 我正在尝试读取文件,并将文件中的单词存储到一个字符串数组中(不包括空格/多个空格)。 Eg my file has the words "this is a test", the program should store into an array arr ["this","is","a","test"] and also increment a variable called wordCount every time it stores a word into the array.
例如,我的文件中有“ this is a test”这个词,程序应将arr [“ this”,“ is”,“ a”,“ test”]存储到数组中,并在每次存储a时增加一个名为wordCount的变量字放入数组。
I understand that i can use 我知道我可以使用
fileContents.split("\\s+")
but that does not increment wordCount each time it adds a word into the array. 但这不会在每次将单词添加到数组中时增加wordCount。 I'm thinking a for loop will do the job but i don't know how.
我在想for循环会完成这项工作,但我不知道如何做。
Any help is appreciated. 任何帮助表示赞赏。 Thanks.
谢谢。
You can iterate the result of the split call and add one to the word count in the same iteration: 您可以迭代split调用的结果,并在同一迭代中将单词计数加1:
String fileContents = "this is a test";
int wordCount = 0;
for (String word: fileContents.split("\\s+")) {
System.out.println(word);
wordCount++;
System.out.println(wordCount);
}
You should add the storage in the array structure each time you have a new word. 每次有新单词时,都应在数组结构中添加存储。
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"/Users/pankaj/Downloads/myfile.txt"));
String line = reader.readLine();
int count = 0;
while (line != null) {
String[] array = line.split("\\s+");
count = count + array.length;
line = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Here I get the line by line so you can add additional functionality per line. 在这里,我逐行获取,因此您可以为每行添加其他功能。 Also get the count by count variable.
还可以通过count变量获取count。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.