计算字母数字字符的出现次数并以图形方式打印

swe*_*men 7 java string

我有一个字符串,我想计算所有字母和数字的出现次数,并想创建一个图表,以便我可以用图形方式查看事件.

例如:

String sentence = "ABC ABC ABC 123"

A (3) * * *
B (3) * * *
C (3) * * *
D
.
.
Run Code Online (Sandbox Code Playgroud)

我的思维方式:

  1. 计算字符串中的所有数字和字母
  2. 打印所有星号乘以这个数字(遗憾的是我无法在String中将String与int相乘)

我认为有两种计算角色的方法.我可以使用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通过zCounter0counter9counter
  • 我必须制作另一个for循环来打印星号!

我不是要求在这里找到答案,我只是在寻找一些好方向,因为我被困住了.

cru*_*ush 8

没有必要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)

注意事项

在决定如何解决此问题时,需要考虑以下事项.

  • 你是否总能知道需要提前跟踪哪些角色,或者有时候想跟踪任何角色?在后一种情况下,阵列不适合您; 您需要使用像TreeMap或HashMap这样的高级数据结构.
  • 你是否总是计算特定chars的出现次数,而不是Strings?如果你必须修改它来计算Strings,那么使用String indexesmap技巧也不适合你.
  • 您是否正在学习课程中的特定数据结构?通常会将这样的问题分配给学生,以了解如何应用特定概念.正如@kyle建议的那样,您应该尝试使用您正在学习或已经了解的数据结构.有时候使用你尚未学到的结构可能会让你陷入困境,或者至少降低成绩.