Java String Substring Count countSubstrings(String string, String sub)

Here you can find the source of countSubstrings(String string, String sub)

Description

Counts the number of substring in a string

License

Open Source License

Parameter

Parameter Description
string String in which to look for substrings
sub Substring to look for in a string

Return

The count of substrings in a string

Declaration

public static int countSubstrings(String string, String sub) 

Method Source Code

//package com.java2s;
/*//from w  ww  . j a  v a 2s  . co m
 * Sonar Delphi Plugin
 * Copyright (C) 2011 Sabre Airline Solutions
 * Author(s):
 * Przemyslaw Kociolek (przemyslaw.kociolek@sabre.com)
 * Michal Wojcik (michal.wojcik@sabre.com)
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02
 */

public class Main {
    /**
     * Counts the number of substring in a string
     * 
     * @param string
     *          String in which to look for substrings
     * @param sub
     *          Substring to look for in a string
     * @return The count of substrings in a string
     */
    public static int countSubstrings(String string, String sub) {
        int count = 0;
        int index = -1;
        while ((index = string.indexOf(sub, index + 1)) != -1) {
            ++count;
        }
        return count;
    }
}

Related

  1. countSubstring(final String text, final String substring)
  2. countSubString(String str, String substr)
  3. countSubstring(String string, String substring)
  4. countSubString(String strToFind, String strSearch)
  5. countSubstringOccurrances(String s1, String SubString)