Saturday 13 December 2014

Given a string as Input check the maximum number of a character appears in the string

public class CheckMaxChar {
   
    static String testcase1="triseeect coders";
    public static void main(String a[]){
        CheckMaxChar testinstances=new CheckMaxChar();
       char result=testinstances.checkMax(testcase1);
        System.out.println(result);
    }

    public char checkMax(String str) {
        int greater=0;//each time a new char will be greater if this value changes
        int count=0;//only count the number of occurence of each char
        char max=' ';//return the max of all char
        char temp=' ';//store the first letter of a string
        int i=0;
       
        while(str.length()>0){//each time the len of string is decreasing by replacing checking char with whitespace
            temp=str.charAt(i);//extract the first char
            String stringValueOf = String.valueOf(temp);//convert that to string
            System.out.println(i+"stringValueOf  iss   :"+stringValueOf);
            for(int j=0;j<str.length();j++){//check the input char number of appearnce
                if(str.regionMatches(j, stringValueOf, 0, stringValueOf.length())){
                    count++;//increase each time it found one of the char
                   
                   
                    System.out.println(j+"temp isss:"+temp);
                    System.out.println("greater is   :"+greater);
                    System.out.println("count is     :"+count);
                }
               
            }
       
            str=str.replace(stringValueOf," ");//replace the checked char with whitespace
            str=str.replaceAll("\\s+","");//wipe out all whhite space
            System.out.println("now the string is "+str);
       
       
           if(count>greater){//check the current char appearence with preveous greater char appearence
               greater=count;
               System.out.println("now the greater is   :"+greater);
               max=temp;//change the max char
               System.out.println("max is  :"+max);
               System.out.println("-----------------------------");
               count=0;
               i=0;
           }
          
           
        } 
   
   
    return max;
    }
   
}

No comments:

Post a Comment