Java Program to Count The Occurences Of Character In a String

Get a String and a character then count the occurrence of character in the string.

Sample Input 1:

Hello

l

Sample Output 1:

2

Try your Solution

Strongly recommended to Solve it on your own, Don't directly go to the solution given below.

public class Hello { public static void main(String args[]) { //Write your code here } }

Program or Solution

				
			
					
//Count The Occurences Of Given Character In A String ...

import java.util.*;

class Program
{
 public static void main(String args[])
 {
 String word;
 char ch;
  
 Scanner sc=new Scanner(System.in);

 System.out.println("Enter The Word:");  
 word=sc.nextLine();  

 int len1=word.length();
 int i,count=0;

 System.out.println("Enter The Character:");
 ch=sc.next().charAt(0); 
 
 System.out.println("The Occurences Of Character Is:");
 for(i=0;i<len1;i++)
 {
 if(ch==word.charAt(i))
 {
 count++;
 }

 }
 System.out.println(" "+count);

 }
}
			
				
			

Program Explanation

Comments