Returns the count of how many times search String occurs in string . - Android java.lang

Android examples for java.lang:String Contains

Description

Returns the count of how many times search String occurs in string .

Demo Code


//package com.java2s;

public class Main {
    /**//from w  w  w . j  a v a 2s.  co  m
     * Returns the count of how many times {@code searchString} occurs in {@code str}.
     */
    public static int countOccurencesIn(String str, String searchString) {
        int count = 0;
        int index = 0;

        while (str.indexOf(searchString, index) >= index) {
            count++;
            index = str.indexOf(searchString, index)
                    + searchString.length();

            if (index > str.length()) {
                break;
            }
        }

        return count;
    }
}

Related Tutorials