FREQUENCY OF A CHARACTER IN A STRING
We have created this java program that will count occurrence of a inputted character in given string . This program will result a number that will show you frequency of that character.
JAVA CODE :)
import java.util.Scanner;
public class Occurrence
{
public static void main(String[] args)
{
String str;
char ch;
int i,c=0,flag=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a String:");
str=sc.nextLine();
System.out.print("Enter a character:");
ch=sc.next().charAt(0);
sc.close();
for(i=0;i<str.length();i++)
{
if(str.charAt(i)==ch)
{
flag=1;
c=c+1;
}
}
if(flag==1)
{
System.out.print("Character "+ch+" is occured in String "+c+" times.");
}
else
{
System.out.print("Character "+ch+" is not present in String.");
}
}
}
0 Comments