我有一个字符串,我想计算所有字母和数字的出现次数,并想创建一个图表,以便我可以用图形方式查看事件.
例如:
String sentence = "ABC ABC ABC 123"
A (3) * * *
B (3) * * *
C (3) * * *
D
.
.
Run Code Online (Sandbox Code Playgroud)
我的思维方式:
我认为有两种计算角色的方法.我可以使用charAt()方法或toCharArray()循环遍历字符串或数组并计算字母数.
例如:
aCounter = 0;
bCounter = 0;
char ch = sentence.charAt(i);
for (i = 0; i < sentence.length(); ++i) {
if (ch == 'a') {
aCounter++;
}
if (ch == 'b') {
bCounter++;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,我有这个方法的多个问题:
aCounter通过zCounter加0counter通9counter我不是要求在这里找到答案,我只是在寻找一些好方向,因为我被困住了.
没有必要HashTable/HashMap/HashSet为此而努力.
您知道提前跟踪哪些字符,因此您可以使用数组.
我想计算所有字母和数字的出现次数
创建一个要跟踪的字符串,然后初始化一个数组.
String sentence = "ABC ABC ABC 123";
//Make a map of all the characters you want to track.
String indexes = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//Initialize an array to the size of the possible matches.
int[] count = new int[indexes.length()];
//Loop through the sentence looking for matches.
for (int i = 0; i < sentence.length(); i++) {
//This will get the index in the array, if it's a character we are tracking
int index = indexes.indexOf(sentence.charAt(i));
//If it's not a character we are tracking, indexOf returns -1, so skip those.
if (index < 0)
continue;
count[index]++;
}
Run Code Online (Sandbox Code Playgroud)
然后你可以用这个打印出来:
for (int i = 0; i < count.length; i++) {
if (count[i] < 1)
continue;
System.out.println(String.format("%s (%d) %s",
indexes.charAt(i),
count[i],
//This little bit of magic creates a string of nul bytes, then replaces it with asterisks.
new String(new char[count[i]]).replace('\0', '*')));
}
Run Code Online (Sandbox Code Playgroud)
如果您对该new String(new char[count[i]]).replace('\0', '*'))位不熟悉,则可以在尝试输出之前使用a StringBuilder来构建星号String.您可以在下面看到@mike的示例,以获得一个很好的例子.
1 (1) *
2 (1) *
3 (1) *
A (3) ***
B (3) ***
C (3) ***
Run Code Online (Sandbox Code Playgroud)
在决定如何解决此问题时,需要考虑以下事项.
chars的出现次数,而不是Strings?如果你必须修改它来计算Strings,那么使用String indexesmap技巧也不适合你.| 归档时间: |
|
| 查看次数: |
16639 次 |
| 最近记录: |