我想计算输入网址中的所有字母。我不想区分大写或小写字母。 a的总量将以整数形式存储在total[0]中,b的总量将存储在total[1]中,依此类推。
知道如何使用 InputStream 实现这一目标吗?
public static int[] letterFrequency(String url) throws IOException {
InputStream inn= new BufferedInputStream((new URL(url)).openStream());
char[] c= {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'æ', 'ø', 'å'};
int[] total= new int[29];
for(int i= 0; i< c.length; i++) {
int counter= 0;
while(inn.available()!= 0) {
if(inn.read()== c[i])
counter++;
}
total[i]= counter;
}
return total;
}
编辑:
谢谢大家的回答!你很棒!! ;)
最佳答案
不要使用流
。这些是为了读取 byte
。如果需要字符,请使用 Reader
。 byte
可能适用于 ASCII,但字符最长可达 4 个字节,并且可能有不同的编码。
public static int[] letterFrequency(String url) throws IOException {
Reader inn = new InputStreamReader(new BufferedInputStream((new URL(url)).openStream()), "UTF-8");
char[] c = {
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z', 'æ', 'ø', 'å'
};
String chars = new String(c);
int[] total = new int[c.length];
int read;
while ((read = inn.read()) != -1) {
read = Character.toLowerCase(read);
int index = chars.indexOf(read);
if (index != -1) {
total[index]++;
}
}
return total;
}
关于java - 如何使用java计算InputStream的char?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18772083/