- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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