[英]Output one occurence of a character in a string c#
该程序应只输出一个字符出现在字符串中的次数,然后指定该字符串中出现字符的数目。 应根据该特定字符的出现次数以升序排序。 除(char)i
部分外,它都在工作。 它与ASCII码有关吗?
所需输出:
b:1
d:1
a2
s:2
代码的输出:
ü:1
ý:1
þ:2
ÿ:2
public class HuffmanCode {
static String string;
static Scanner input = new Scanner(System.in);
public static void main(String args[]){
System.out.print("Enter a string: ");
string = input.nextLine();
int count[] = countOccurence(string);
Arrays.sort(count);
for (int i = 0; i < count.length; i++) {
if (count[i] > 0)
System.out.println((char)i + ": " + count[i]);
}
}
public static int[] countOccurence(String str){
int counts[] = new int[256];
for(int i=0;i<str.length();i++){
char charAt = str.charAt(i);
counts[(int)charAt]++;
}
return counts;
}
}
在Java 8中,您可以使用Stream
API并执行以下操作:
String input = "ababcabcd" ;
input.chars() // split the string to a stream of int representing the chars
.boxed() // convert to stream of Integer
.collect(Collectors.groupingBy(c->c,Collectors.counting())) // aggregate by counting the letters
.entrySet() // collection of entries (key, value), i.e. char, count
.stream() // corresponding stream
.sorted(Map.Entry.comparingByValue()) // sort by value, i.e. by number of occurence of letters
.forEach(e->System.out.println((char)(int)e.getKey() + ": " + e.getValue())); // Output the result
结果将是:
d: 1
c: 2
a: 3
b: 3
希望对您有所帮助。
编辑:假设您的输入是
String input = "ababc\u0327abçd" ;
在这种情况下,我们将ababçabçd
作为输入,并且需要进行规范化以确保我们正确地计数具有不同表示形式的相同字母。 为此,我们使用JDK6中引入的Normalization预处理input
字符串:
input = Normalizer.normalize(input, Form.NFC);
您可以结合使用TreeMap
和自定义Comparator
这是一个例子
String test = "ABBCCCDDDDEEEEEFFFFFF";
Map<Character, Integer> map = new HashMap<>();
for (Character c : test.toCharArray()) {
if (!map.containsKey(c)) map.put(c, 0);
map.put(c, map.get(c) + 1);
}
Map<Character, Integer> tMap = new TreeMap<>(new MyComparator(map));
tMap.putAll(map);
for (Map.Entry<Character, Integer> entry : tMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
这是MyComparator
的实现
class MyComparator implements Comparator<Object> {
Map<Character, Integer> map;
public MyComparator(Map<Character, Integer> map) {
this.map = map;
}
public int compare(Object o1, Object o2) {
if (map.get(o1).equals(map.get(o2)))
return 1;
else
return (map.get(o1)).compareTo(map.get(o2));
}
}
创建一个列表并对其进行排序,而不是对count
进行排序。
List<int[]> list = new ArrayList<>();
for (int i = 0; i < count.length; i++) {
if (count[i] > 0)
list.add(new int[] {i , count[i]});
}
Collections.sort(list, Comparator.comparing(a -> a[1]));
for (int[] a : list) {
System.out.println((char)a[0] + ": " + a[1]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.