Sunday, March 29, 2020

To Print occurence of a character in given String in java.

To print Occurrence of  a given character is a simple thing. We need compare each character of a given string with the character we need to compare. and if both matches than we have to increase the counter by 1.
import java.util.Scanner;

public class Accurence_char {
 
 public static void main(String[] args) {
  Scanner sc=new Scanner(System.in);
  System.out.print("enter the string:--");
  String str=sc.next();
  char check='o';
  int count=0;
  
 for(int i=0;i<str.length();i++)
 {

  if(str.charAt(i)==check)
  {
   count++;
  }
  
  
 }
 
 System.out.println("occurence of "+check+" in given string is:"+count);
 
 }
 

}

No comments:

Post a Comment