Home Java Java-tips Data Strings 96string_examples Java: Example - Count occurences

Ask Questions?

View Latest Questions

Advertisement


 
 

Java: Example - Count occurences
Posted on: March 11, 2008 at 12:00 AM
Problem: Count the number of times one string is found in another.

Java: Example - Count occurences

Problem: Count the number of times one string is found in another.
//-------------------------------------------- count()
int count(String base, String searchFor) {
    int len   = searchFor.length();
    int result = 0;
  
    if (len > 0) {  // search only if there is something
        int start = base.indexOf(searchFor);
        while (start != -1) {
            result++;
            start = base.indexOf(searchFor, start+len);
        }
    }
    return result;
}
The loop is a natural for loop, but this would produce a very long line.
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-10-29
Advertisement


DMCA.com