Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

Java String Exercises: Find the second most frequent character in a given string

Java String: Exercise-34 with Solution

Write a Java program to find the second most frequent character in a given string.

Pictorial Presentation:

Java String Exercises: Find the second most frequent character in a given string

Sample Solution:

Java Code:

import java.util.*;
public class Main {
 static final int NOOFCHARS = 256;
 static char get2ndMostFreq(String str1) {

  int[] ctr = new int[NOOFCHARS];
  int i;
  for (i = 0; i < str1.length(); i++)
   (ctr[str1.charAt(i)]) ++;

  int ctr_first = 0, ctr_second = 0;
  for (i = 0; i < NOOFCHARS; i++) {
   if (ctr[i] > ctr[ctr_first]) {
    ctr_second = ctr_first;
    ctr_first = i;
   } else if (ctr[i] > ctr[ctr_second] && ctr[i] != ctr[ctr_first])
    ctr_second = i;
  }
  return (char) ctr_second;
 }
 public static void main(String args[]) {
  String str1 = "successes";
  System.out.println("The given string is: " + str1);
  char res = get2ndMostFreq(str1);
  if (res != '\0')
   System.out.println("The second most frequent char in the string is: " + res);
  else
   System.out.println("No second most frequent character found in the string.");
 }
}

Sample Output:

The given string is: successes
The second most frequent char in the string is: c

Flowchart:

Flowchart: Java String Exercises - Find the second most frequent character in a given string

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to find all interleavings of given strings.
Next: Write a Java program to print all permutations of a given string with repetition.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe