posts - 110, comments - 101, trackbacks - 0, articles - 7
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

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

Posted on 2011-05-26 13:51 云云 阅读(1748) 评论(0)  编辑  收藏
    /**
     * 取得指定子串在字符串中出现的次数。
     * <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;
    }

只有注册用户登录后才能发表评论。


网站导航: