» » Java Program to Count the number of occurrences of a char in a String?



Solution #1:

  1. package com.javatutorial;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class CountNumberofChars {
  6.  
  7.  public static void main(String[] args) {
  8.   
  9.  String str = "";
  10.  
  11.  Scanner in= new Scanner(System.in);
  12.  System.out.println("Please enter a String");
  13.  
  14.  str=in.nextLine();
  15.  
  16.  System.out.println("Please enter a Character");
  17.  String chr=in.next();
  18.  
  19.  int charCount = str.length() - str.replaceAll("a", "").length();
  20.  
  21.  System.out.println("Number of occurances of given character:"+charCount);
  22.  
  23. }

  24. }



Output:

  1. Please enter a String
  2. Java
  3. Please enter a Character
  4. a
  5. Number of occurances of given character:2


Solution #2:


  1. package com.javatutorial;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class CountNumberofChars {
  6.   
  7. public static int countOccurrences(String find, String string)
  8. {
  9. int count = 0;
  10. int indexOf = 0;
  11.  
  12. while (indexOf > -1)
  13. {
  14.     indexOf = string.indexOf(find, indexOf + 1);
  15.     if (indexOf > -1)
  16.             count++;
  17.       }
  18. return count;
  19.  }

  20.  public static void main(String[] args) {
  21.   
  22.  int charCount=countOccurrences("a", "Instance of Java");
  23.  
  24.  System.out.println("Number of occurrences of given character:"+charCount);
  25.  
  26. }

  27. }

Output:

  1. Number of occurrences of given character: 3

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

2 comments for Java Program to Count the number of occurrences of a char in a String?

  1. in solution#2

    the first letter will not be countable,for example "hi this Ram" -in this sentence i want to search letter 'h'(there are 2 h's) but it gives only one ....


    while (index > -1) {
    index = string.indexOf(find, index);
    if (index > -1) {
    count++;
    index++;
    }
    }

    then it will work

    ReplyDelete

Select Menu