Java program to find the character that appears the most number of times in a String?

前端 未结 8 943
慢半拍i
慢半拍i 2020-12-22 13:03

So here\'s the code I\'ve got so far...

import java.util.Scanner;
class count{
    public static void main(String args[]){
        Scanner s=new Scanner(Syst         


        
8条回答
  •  攒了一身酷
    2020-12-22 13:17

    I would do something like this

        String str = "yabbadabbadoo";
        Hashtable ht = new Hashtable() ;
        for (int x = 0; x < str.length(); x++) {
            Integer idx = (int) str.charAt(x);
            Integer got = ht.get(idx);
            if (got == null) {
                ht.put(idx, 1);
            } else {
                ht.put(idx, got.intValue() + 1);
            }
        }
    
        int max = 0;
        char ch = '-';
        Enumeration keys = ht.keys();
        while (keys.hasMoreElements()) {
            Integer idx = keys.nextElement();
            int count = ht.get(idx);
            if (count > max) {
                ch = (char) idx.intValue();
                max = count;
            }
        }
    
        System.out.print("[" + ch + "]");
        System.out.println(" Max " + max);
    

    Keep in mind about upper and lower case characters

提交回复
热议问题