 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count how many times the substring appears in the larger String in Java
Let’s say we have the following string.
String str = "Learning never ends! Learning never stops!";
In the above string, we need to find out how many times the substring “Learning” appears.
For this, loop until the index is not equal to 1 and calculate.
while ((index = str.indexOf(subString, index)) != -1) { subStrCount++; index = index + subString.length(); } The following is an example.
Example
public class Demo {    public static void main(String[] args) {       String str = "Learning never ends! Learning never stops!";       System.out.println("String: "+str);       int subStrCount = 0;       String subString = "Learning";       int index = 0;       while ((index = str.indexOf(subString, index)) != -1) {          subStrCount++;          index = index + subString.length();       }       System.out.println("Substring "+subString+" found "+subStrCount+" times!");    } }  Output
String: Learning never ends! Learning never stops! Substring Learning found 2 times!
Advertisements
 