Counts the number of matches that exist in the string - Java java.lang

Java examples for java.lang:String Search

Description

Counts the number of matches that exist in the string

Demo Code

/* Copyright (c) 2001 - 2007 TOPP - www.openplans.org. All rights reserved.
 * This code is licensed under the GPL 2.0 license, available at the root
 * application directory./*  w  ww. ja va2s  .  co m*/
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        String str = "java2s.com";
        String sub = "java2s.com";
        System.out.println(countMatches(str, sub));
    }

    /**
     * Counts the number of matches that exist in the string
     * 
     * @param str
     *            - the main string to be matched against
     * @param sub
     *            - the substring to be match
     * @return - count of the number of matches
     */
    public static int countMatches(String str, String sub) {
        if (str.length() == 0 || sub.length() == 0) {
            return 0;
        }
        int count = 0;
        int idx = 0;
        while ((idx = str.indexOf(sub, idx)) != -1) {
            count++;
            idx += sub.length();
        }
        return count;
    }
}

Related Tutorials