我有一个字符串,我想计数所有字母和数字的出现,并希望创建一个图形,这样我就可以以图形的方式看到发生的情况。
例如:
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映射技巧也不会对您起作用。发布于 2013-09-12 14:26:58
下面是一些让你开始的提示:
发布于 2013-09-12 14:27:27
您可以使用另一种方法,而不是循环一次计算金额,再循环一次打印星号:
Map<Character,String> results = new HashMap<Character, String>();然后,每次迭代时,检查映射是否包含该字符的数据,如果没有,则初始化它。伪码:
If the map contains data for the key
Obtain the data for the character
append a new asterisk
Else
Create a String with an asterisk
Append an asterisk
Put the String with the character as key如果您曾经需要星号的数量作为一个数字,您总是可以获得String的大小(假设您没有放置任何空格)。
更新
作为一种改进,考虑到我与@crush分享的评论,两个调整可以改进逻辑:
StringBuilder而不是String__:避免不必要的文字创建。TreeMap而不是HashMap__:它将给地图以适当的顺序,允许对其内容进行排序打印。如果有足够的空间(和知识)来证明它们的使用,则由OP来添加这些额外的内容。
https://stackoverflow.com/questions/18766857
复制相似问题