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

前端 未结 8 1001
慢半拍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:18

        String sent = "asdAdFfaedfawghke4";//s.nextLine();      
        int length = sent.length();
        char frequentChar = ' ';
        int maxLength = 0;
        for (int i = 0; i < length; i++) {
            char currentChar = sent.charAt(0);
            sent = sent.replaceAll(currentChar + "", "");//remove all charactes from sent
            if (maxLength < (length - sent.length())) {
                frequentChar=currentChar;
                maxLength = length - sent.length();
            }
            System.out.println("Char : " + currentChar + " Occurance " + (length - sent.length()));
            length = sent.length();
        }
        System.out.println("Max Occurance : " + maxLength);
    

    Output :

    Char : a Occurance 3
    Char : s Occurance 1
    Char : d Occurance 3
    Char : A Occurance 1
    Char : F Occurance 1
    Char : f Occurance 2
    Char : e Occurance 2
    Frequent Char : a
    Max Occurance : 3
    

提交回复
热议问题