java统计一个文件(d:\a.txt)中出现过多少单词,以a开头的单词有多少个?
时间: 2024-03-02 20:50:38 浏览: 99
以下是Java代码实现:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class WordCount {
public static void main(String[] args) {
String filePath = "d:/a.txt";
int totalWordCount = 0;
int aWordCount = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] words = line.split("\\s+");
for (String word : words) {
totalWordCount++;
if (word.startsWith("a") || word.startsWith("A")) {
aWordCount++;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Total word count: " + totalWordCount);
System.out.println("Word count starting with 'a': " + aWordCount);
}
}
```
该程序首先读取指定文件中的每一行,然后使用空格作为分隔符将每行拆分成单词数组。接着遍历每个单词,分别统计总单词数和以'a'或'A'开头的单词数。最后输出结果。
阅读全文
相关推荐















