» » Count the number of occurrences of a character in a String?

  1. package com.instaceofjava; 
  2.  
  3. public class StringCount {
  4.  
  5. public static void main(String[] args)
  6. {
  7.  
  8. String str = "abcdcabcdacbdadbca";
  9.  
  10.     String findStr = "b";
  11.     int lastIndex = 0;
  12.     int count = 0;
  13.  
  14.     while (lastIndex != -1) {
  15.  
  16.     lastIndex = str.indexOf(findStr, lastIndex);
  17.  
  18.     if (lastIndex != -1) {
  19.     count++;
  20.     lastIndex += findStr.length();
  21.  
  22.     }
  23.     }
  24.     System.out.println(count);
  25. }
  26.  
  27. }


Output:
  1. 4

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

No comments

Leave a Reply

Select Menu