File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Scanner ;
2
+
3
+ class MostFrequentCharacter {
4
+ // Main method
5
+ public static void main (String [] args ) {
6
+ Scanner input = new Scanner (System .in );
7
+
8
+ System .out .print ("Enter a string: " );
9
+ String str = input .nextLine ();
10
+
11
+ // Method to find the most frequent character in a string
12
+ char result = mostFrequentChar (str );
13
+
14
+ System .out .println ("Most frequent character in the string: " + result );
15
+ }
16
+
17
+ // Method to find the most frequent character in a string
18
+ public static char mostFrequentChar (String str ) {
19
+ // Remove all leading and trailing whitespace, and in between spaces
20
+ str = str .replaceAll ("\\ s" , "" ).trim ();
21
+
22
+ int [] freq = new int [256 ];
23
+
24
+ // Count frequency of each character
25
+ for (int i = 0 ; i < str .length (); i ++) {
26
+ char ch = str .charAt (i );
27
+ freq [ch ]++;
28
+ }
29
+
30
+ // Find the character with maximum frequency
31
+ char mostFrequentChar = '\0' ;
32
+ int maxFreq = 0 ;
33
+ for (int i = 0 ; i < freq .length ; i ++) {
34
+ if (freq [i ] > maxFreq ) {
35
+ maxFreq = freq [i ];
36
+ mostFrequentChar = (char ) i ;
37
+ }
38
+ }
39
+
40
+ return mostFrequentChar ;
41
+ }
42
+ }
You can’t perform that action at this time.
0 commit comments