我有一个字符串,我想计数所有字母和数字的出现,并希望创建一个图形,这样我就可以以图形的方式看到发生的情况。
例如:
String sentence = "ABC ABC ABC 123"
A (3) * * *
B (3) * * *
C (3) * * *
D
.
.我的想法是:
我认为有两种计算字符的方法。我既可以使用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++;
}
}然而,对于这种方法,我有多个问题:
aCounter通过zCounter,0counter通过9counter我不是在要求一个固定的答案,我只是在找一些好的方向,因为我被困住了。
发布于 2013-09-12 14:24:24
没有必要为此做一个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]++;
}然后你可以用这个打印出来:
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', '*')));
}如果您不习惯使用new String(new char[count[i]]).replace('\0', '*'))位,那么在尝试输出星号String之前,可以使用StringBuilder构建星号String。您可以在下面看到@mike的示例,以获得一个很好的示例。
输出
1 (1) *
2 (1) *
3 (1) *
A (3) ***
B (3) ***
C (3) ***注意事项
在决定如何解决这个问题时,以下是一些需要考虑的问题。
chars的出现次数,而不是Strings?如果您必须修改它以计数Strings,那么使用String indexes映射技巧也不会对您起作用。https://stackoverflow.com/questions/18766857
复制相似问题