![](/img/trans.png)
[英]How to count the occurrence of each letter of the alphabet from a text file in Java?
[英]How to count occurrence of each character in the alphabet with a file
我想知道如何啟動一個程序,該程序讀取文件並逐行計算字母表中每個字母的出現。我知道我想使用一個保存字母的數組,但我不是確保如何閱讀每一行,然后打印出每個字母出現的計數。
BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
int ch;
char charToSearch='a';
int counter=0;
while((ch=reader.read()) != -1) {
if(charToSearch == (char)ch) {
counter++;
}
};
reader.close();
System.out.println(counter);
參考: 盤點字母出現
嘗試這個
public void countOccurence() {
BufferedReader reader
= new BufferedReader(new FileReader("somefile.txt"));
String text = "";
while((ch=reader.read()) != -1) {
text = text +ch;
};
reader.close();
for(Character a :"abcdefghijklmnopqrstuvwxyz0123456789".toCharArray())
{
int ch;
char charToSearch=a;
int counter=0;
for(Character b : text.toCharArray())
{
if(charToSearch == (char)b) {
counter++;
}
}
System.out.pritln("Character: " +charToSearch+ " occurs " + counter
+ " times.");
}
}
標記為up,如果它對您有用:)
public void count() throws Exception {
int[] array = new int[26];
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
int ch;
while((ch = br.read()) != -1) {
if (ch > 64 && ch < 97) // Upper case letters
ch += 32; // to get the ascii value of the letter in lowercase
if(-1 < ch-97 && ch-97 < 26)
array[ch-97] += 1;
}
br.close();
int i = 0;
for (char chr = 'a'; chr <= 'z'; chr++) {
System.out.printf("%s --> %d\n", chr, array[i]);
i++;
}
}
BufferedReader reader = new BufferedReader(new FileReader("somefile.txt"));
int ch;
Map<char, int> charCount = new Map<char, int>();
while((ch=reader.read()) != -1) {
if(charCount.contains(ch)) {
charCount.put(ch, charCount.get(ch)++);
} else {
charCount.put(ch, 1);
}
}
reader.close();
for(String key: charCount.keySet())
System.out.println(key + " - " + charCount.get(key));
System.out.println();
這將為文件中的每個字符保留一個計數器。 如果要將此設置限制為字母,則可以通過在將其放入charCount
之前檢查ch
是否存在字母來輕松charCount
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.