Java Program To Find Frequency Of Character In String
Chapter:
Interview Programs
Last Updated:
28-09-2017 16:01:57 UTC
Program:
/* ............... START ............... */
public class JavaFindFrequencyOfCharacter {
public static void main(String[] args) {
String str = "welcome to the world of programming.";
char ch = 'e';
int frequency = 0;
for (int i = 0; i < str.length(); i++) {
if (ch == str.charAt(i)) {
++frequency;
}
}
System.out.println("Frequency of " + ch + " = " + frequency);
}
}
/* ............... END ............... */
Output
Notes:
-
First we initialize the string str with value "welcome to the world of programming."
- Next step loop each character in the string, using charAt() function which takes the index and returns the character in the given index.
- We compare each character to the given character ch. If it's a match, we increase the value of frequency by 1.
- Last we will print the frequency using System.out.println.
Tags
Find Frequency Of Character In String, Java, Interview