比如,
str1 = "acdacd yyyojo acdadd"
中含有 acd的个数,
结果应该是3。先谢了,string中找不到相关的方法。

解决方案 »

  1.   

    楼上的 如果 字符串 是 acd的时候就不对了
      

  2.   

    看了下,原来是split的问题
    修正如下:static int getSubStringLength(String str,String substring)
    {
        int 重复次数=str.split(substring).length-1;
        if(str.endsWith(substring))
          重复次数++;
        return 重复次数;
    }
      

  3.   

    问一下,"aaaaaa"中包含多少个"aa"
    3个,即
    "aa...."
    "..aa.."
    "....aa"
    还是5个
    "aa...."
    ".aa..."
    "..aa.."
    "...aa."
    "....aa"建议用apache的jakarta commons lang包的
    StringUtils.countMatches() StringUtils.countMatches(null, *)       = 0
     StringUtils.countMatches("", *)         = 0
     StringUtils.countMatches("abba", null)  = 0
     StringUtils.countMatches("abba", "")    = 0
     StringUtils.countMatches("abba", "a")   = 2
     StringUtils.countMatches("abba", "ab")  = 1
     StringUtils.countMatches("abba", "xxx") = 0
     StringUtils.countMatches("aaaaaa", "aa") = 3
      

  4.   

    再修正if(str.equals(substring))
       return 1;
      

  5.   

    用substring 从要查找的串中写个
      

  6.   

    public static int countMatches(String str, String sub) {
            if (isEmpty(str) || isEmpty(sub)) {
                return 0;
            }
            int count = 0;
            int idx = 0;
            while ((idx = str.indexOf(sub, idx)) != -1) {
                count++;
                idx += sub.length();
            }
            return count;
        }public static boolean isEmpty(String str) {
            return str == null || str.length() == 0;
        }
      

  7.   

    split是个正则表达式,按照acd把你原来的字符串拆成多个字符串,然后你在进行判断,很简单的
      

  8.   

     * StringUtils.countMatches(null, *)       = 0
         * StringUtils.countMatches("", *)         = 0
         * StringUtils.countMatches("abba", null)  = 0
         * StringUtils.countMatches("abba", "")    = 0
         * StringUtils.countMatches("abba", "a")   = 2
         * StringUtils.countMatches("abba", "ab")  = 1
         * StringUtils.countMatches("abba", "xxx") = 0public static int countMatches(String str, String sub) {
            if (isEmpty(str) || isEmpty(sub)) {
                return 0;
            }
            int count = 0;
            int idx = 0;
            while ((idx = str.indexOf(sub, idx)) != -1) {
                count++;
                idx += sub.length();
            }
            return count;
        }