取得指定子串在字符串中出现的次数

     /** */ /**
     * 取得指定子串在字符串中出现的次数。
     * <p/>
     * <p>
     * 如果字符串为<code>null</code>或空,则返回<code>0</code>。
     * <pre>
     * StringUtil.countMatches(null, *)       = 0
     * StringUtil.countMatches("", *)         = 0
     * StringUtil.countMatches("abba", null)  = 0
     * StringUtil.countMatches("abba", "")    = 0
     * StringUtil.countMatches("abba", "a")   = 2
     * StringUtil.countMatches("abba", "ab")  = 1
     * StringUtil.countMatches("abba", "xxx") = 0
     * </pre>
     * </p>
     * 
@param str    要扫描的字符串
     * 
@param subStr 子字符串
     * 
@return 子串在字符串中出现的次数,如果字符串为<code>null</code>或空,则返回<code>0</code>
     
*/

    
public   static   int  countMatches(String str, String subStr)  {
        
if ((str == null|| (str.length() == 0|| (subStr == null|| (subStr.length() == 0)) {
            
return 0;
        }


        
int count = 0;
        
int index = 0;

        
while ((index = str.indexOf(subStr, index)) != -1{
            count
++;
            index 
+= subStr.length();
        }


        
return count;
    }

你可能感兴趣的:(取得指定子串在字符串中出现的次数)