The program starts by defining a static method max_occuring_char() that accepts a string parameter str. It initializes an integer array arr with 250 elements and the length of the input string l.
Then, it iterates through each character in the string using a for loop and increments the corresponding count in the arr array using the ASCII value of the character as the index.
After that, it initializes variables max and res to -1 and a space character respectively. It again iterates through each character in the string using a for loop, checks if the count of the character in the arr array is greater than the current maximum max, and if it is, updates the max and res variables with the new character.
Finally, the method returns the character that occurred the most number of times in the string. The program also defines a main() method that initializes a string variable str with the value "java exercises", prints the original string to the console, calls the max_occuring_char() method to find the character that occurs the most number of times in the string, and prints the result to the console.
public class Max_Occurring { static char max_occuring_char(String str) { int arr[] = new int[250]; int l = str.length(); for (int i = 0; i < l; i++) { arr[str.charAt(i)]++; } int max = -1; char res = ' '; for (int i = 0; i < l; i++) { if (max < arr[str.charAt(i)]) { max = arr[str.charAt(i)]; res = str.charAt(i); } } return res; } public static void main(String[] args) { String str = "java exercises"; System.out.println("Given String is: " + str); System.out.println("Max Occurring Character in String is: " + max_occuring_char(str)); } }
Given String is: java exercises Max Occurring Character in String is: e
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions