Skip to content

Commit 03ee027

Browse files
committed
[Manan] ADD:Finding most frequent character in a string
1 parent 45d0cc5 commit 03ee027

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

MostFrequentCharacter.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
}

0 commit comments

Comments
 (0)