在这里,我有两个字符串来打印每个字符发生了多少次,但我希望结果按降序排列。
public static void main(String[] args) {
TreeMap tm = new TreeMap();
String s = "ajklfajdlkfajsdklfjalljaklsdfjaklsdjf";
int[] counts = new int[128];
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch < 128) {
counts[ch]++;
} else {
System.out.println("out of range");
}
}
for (char c = 0; c < 128; c++) {
if (counts[c] != 0) {
tm.put(counts[c], c);
// System.out.println(c + " occured " + counts[c] + "times");
}
}
for(int i=0;i<tm.size();i++){
System.out.println(tm.get(i));
}
}
这段代码给出的输出为:null,null,null,s,d,但我需要输出为:jlafkds。请指导我。
我的答案可能与其他答案很像,但我努力保持原始代码的精神,他们只是在编写时更快。
package uk.co.puce4.charactercount;
import java.util.Iterator;
import java.util.TreeMap;
import java.util.TreeSet;
public class CharacterCount {
public static void main(String[] args)
{
TreeMap<Character,Integer> tm = new TreeMap<Character,Integer>();
String s = "ajklfajdlkfajsdklfjalljaklsdfjaklsdjf";
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
int count = 1;
if(tm.containsKey(ch)){
count=tm.get(ch) + 1;
}
tm.put(ch, count);
}
TreeSet<CharItem> ts = new TreeSet<CharItem>();
Iterator<Character> it = tm.descendingKeySet().iterator();
while (it.hasNext()){
char ch = (char) it.next();
int count = tm.get(ch);
CharItem ci= new CharItem(ch, count);
ts.add(ci);
}
Iterator<CharItem> it2 = ts.iterator();
while(it2.hasNext()){
CharItem ci=it2.next();
System.out.println(ci.getCh() + " occured " + ci.getCount() + " times");
}
}
}
class CharItem implements Comparable<CharItem>{
private int count;
private char ch;
public CharItem(char c, int i){
count = i;
ch = c;
}
public char getCh() {
return this.ch;
}
public int getCount() {
return this.count;
}
@Override
public int compareTo(CharItem b) {
return b.count - this.count ;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句