如何使用Java在大字符串中查找最常见的字符? [英] how to find the most frequent character in a big string using java?
问题描述
我正在做一项作业,我必须在字符串中找到最常见的四个字符。
i'm working on an assignment that i have to find the most four frequent characters in a string. i write this so far.
import java.util.Scanner;
public class FindTheMostOccur
{
public static void main (String[] args)
{
String input;
String example = "how to find the most frequent character in a big string using java?";
String[] array = new String[example.length()];
for (int i = 97; i < 123; i++)
{
int mostFrequent =0;
for( int j = 0; j < example.length(); j++)
{
if(example.charAt(j) == i)
{
++mostFrequent;
}
}
System.out.println( (char)i + " is showing " + mostFrequent+ " times ");
}
}
}
此示例的输出。
a显示5次
b为显示1次
c显示2次
d显示1次
e显示4倍
f显示2次
g是显示3次
h显示3次
我显示5次
j显示1次
k显示0次
l显示0次
m显示1次
n为显示5次
o显示3次
p显示0次
q显示1倍
r显示4倍
s显示3次
t显示6次
u是sh欠2次
v显示1次
w显示1次
x显示0次
y显示0次
例如:t,a,i,n
in this examle : t, a,i,n
我不需要别人来为我完成程序,但是我需要一些想法来找到最多的四个常用字符在这个例子中。
I DON"T NEED SOMEONE TO COMPLETE THE PROGRAM FOR ME, however i need some ideas how to find the most four frequent character in this example.
推荐答案
如何?
int count[] = new int[1000];// all with zero
然后对字符串中的每个字符进行 count [] ++
Then for each character from the string, do count[]++
like this way
count['c']++;
count['A']++;
最后,找出哪个索引具有最大值。然后只需打印该索引的 ascii
。
At the end, find out which index holds the maximum value. Then just print the ascii
of that index.
这篇关于如何使用Java在大字符串中查找最常见的字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!