How to print the maximum occurred character of a string in Java?

JavaObject Oriented ProgrammingProgramming

A String class can be used to represent the character strings, all the string literals in Java programs are implemented as an instance of the String Class. The Strings are constants and their values cannot be changed (immutable) once created.

In the below program, we can print the maximum occurred character of a given string.

Example

public class MaxOccuredCharacterTest {
   public static void main(String[] args) {
      String str1 = maxOccuredChar("tutorialspoint");
      System.out.println(str1);
      String str2 = maxOccuredChar("AABBAABBCCAABBAA");
      System.out.println(str2);
      String str3 = maxOccuredChar("111222333444333222111");
      System.out.println(str3);
   }
   public static String maxOccuredChar(String str) {
      char[] array = str.toCharArray();
      int maxCount = 1;
      char maxChar = array[0];
      for(int i=0, j=0; i < str.length()-1; i=j) {
         int count = 1;
         while(++j < str.length() && array[i] == array[j]) {
            count++;
         }
         if (count > maxCount) {
            maxCount = count;
            maxChar = array[i];
         }
      }
      return (maxChar + " = " + maxCount);
   }
}

Output

t = 1
A = 2
1 = 3
raja
Published on 22-Aug-2019 17:26:09
Advertisements