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:
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:
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
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework