Play Games

Search This Blog

Thursday, January 6, 2022

How to get the character or characters of a string that repeated most number of times - Salesforce Globe For You

How to get the character or characters of a string that repeated most number of times - Salesforce Globe For You

Solution

Step 1: convert the given string in to an array which holds a single character in each index

Step 2:Prepare a map with Key as character and value as number of times it repeated by iterating the above array based on its size.

Step 3: Get the maximum count any character repeated most by iterating the above map.

Step 4:Iterate the map and get the characters by comparing each value of map with the maximum count calculated in the above step.

Sample Code:

Run the following sample code in developer console

String name ='Salesforce Globe For You';

Map<String,Integer> mapCharacter = new Map<String,Integer>();

//convert name to Character array

List<String> lstCharacter = name.split('');

for(integer i=0; i<lstCharacter.size(); i++) {

    if(string.isNOTBLANK(lstCharacter[i])) {

        String lowerCaseCharacter = lstCharacter[i].toLOWERCASE();

        if(mapCharacter.containsKey(lowerCaseCharacter)) {

            Integer count = mapCharacter.get(lowerCaseCharacter)+1;

            mapCharacter.put(lowerCaseCharacter,count);

        } else {

            mapCharacter.put(lowerCaseCharacter,1);

        }

    }

}

//To get the maximum number of times a character repeated

String mostRepeatedCharacter ='';

integer charMaxRepeatedcount = 0;

for(String s:mapCharacter.keyset()) {

    If(mapCharacter.get(s) > charMaxRepeatedcount) {

        charMaxRepeatedcount = mapCharacter.get(s);

    }

}

// To get Character that repeated most

for(String s:mapCharacter.keyset()) {

    If(mapCharacter.get(s) == charMaxRepeatedcount) {

        if(mostRepeatedCharacter =='') {

            mostRepeatedCharacter = s;

        } else {

            mostRepeatedCharacter = mostRepeatedCharacter+', '+s;

        }

        

    }

}

system.debug('Most Repeating Character or Characters in given String : '+mostRepeatedCharacter);

Output:



No comments:

Post a Comment