Monday 18 October 2021

Find the character element which appears maximum number of times in an String

 //Find the element which appears maximum number of times in an array


import java.util.Arrays;
public class MyClass {
public static void main(String args[]) {

String name="amitrawat";

char[] word=name.toCharArray();

for(int i=0;i<word.length;i++){

for(int j=i+1;j<word.length;j++){
char first=word[i];
char second=word[j];
char temp;

if(first>second){
temp=first;
word[i]=second;
word[j]=temp;
}
}

}

System.out.println("max number : " + String.valueOf(word));


//getting max character and times
char maxchar=word[0];
int times=0;
for(int i=0;i<word.length;i++){

char w=word[i];

if(maxchar==w){
times++;

}else if(maxchar<w){
times=1;
maxchar=w;

}
}

System.out.println("char max : " + maxchar);
System.out.println("char times: " + times);
}
}
OUTPUT
max number : aaaimrttw
char max  : w
char times: 1

1 comment:

  1. // Online Java Compiler
    // Use this editor to write, compile and run your Java code online

    class HelloWorld {
    public static void main(String[] args) {
    System.out.println("Hello, World!");

    // String name="amitrawat";

    String name="Hello, World";
    System.out.println("sorting order : "+String.valueOf(getSorting(name)));

    char[] sortObj=getSorting(name);//sorting order


    //checking the number of highest occurence
    numberOccurence(sortObj);



    }

    static char[] getSorting(String name){

    if(name!=null){
    char[] tempObj=name.toCharArray();
    for(int i=0;ilast){
    temp=first;
    tempObj[i] =last;
    tempObj[j]=first;
    }


    }
    }
    return tempObj;
    }
    return null;
    }

    static void numberOccurence(char[] sortObj){
    int times=1;
    int maxTimesObj=1;
    char maxObj=0;
    char tempObj=0;

    for(int i=0;i<sortObj.length;i++){
    int lastValue=i+1;

    if(lastValue<sortObj.length){
    if(sortObj[i]==sortObj[i+1]){
    tempObj=sortObj[i];
    times++;
    }
    else{
    if(maxTimesObj<times){
    maxTimesObj=times;
    maxObj=tempObj;
    }
    times=1;

    }
    }


    }
    System.out.println("maxnumber : "+maxTimesObj);

    System.out.println("max char : "+maxObj);
    }


    }

    output:
    sorting order : ,HWdellloor maxnumber : 3 max char : l

    ReplyDelete