In this program, you'll learn to find the occurrence (frequency) of a character in a given string.
Program:
import java.util.*;
public class Frequency
{
public static void main(String[] args)
{
String str;
char ch;
int frequency = 0;
Scanner sc=new Scanner(System.in);
System.out.println("Input a sentence:");
str=sc.nextLine();
System.out.println("Input a character to show how many times present:");
ch=sc.next().charAt(0);
for(int i = 0; i < str.length(); i++) {
if(ch == str.charAt(i)) {
++frequency;
}
}
System.out.println("Frequency of " + ch + " = " + frequency);
}
}
Input a sentence:
welcome to java programming
Input a character to show how many times present:
m
Frequency of m = 3
- In the above program, the length of the given string, str, is found using the string method length().
- We loop through each character in the string using charAt() function which takes the index (i) 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.
- In the end, we get the total occurence of a character stored in frequency and print it.