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 are here to help you learn! Feel free to leave your comments and suggestions in the comment section. If you have any doubts, use the search box on the right to find answers. Thank you! 😊
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu