代码如下~
public int countSubstring() {
String p = "abababa";
String c = "a";
int sum = 0;
int len = p.length();
for (int i = 0; i < len; i++) {
if (p.indexOf(c) >= 0) {
sum++;
p = p.substring((p.indexOf(c) + 1));
}

} return sum;
} public static void main(String[] args) {
// TODO Auto-generated method stub
HelloWorld1 hello=new HelloWorld1();
hello.countSubstring();

}//为什么在运行时不能实现调用?
请高手指教

解决方案 »

  1.   

    你的代码没问题,可以正常运行,只是没打印结果:System.out.println(hello.countSubstring());
    其实可以不用循环,这样写:
        public int countSubstring()
        {
            String p = "abababa";
            String c = "a";
            if (p.endsWith(c))
            {
                return p.split(c).length;
            }
            else
            {
                return p.split(c).length -1;
            }
        }
      

  2.   

    看楼主的代码很像是求c在p中的数量啊
    没必要这么麻烦 package com.keeya.util;public class Test {
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    HelloWorld1 hello = new HelloWorld1();
    System.out.println(hello.countSubstring());
    }
    }class HelloWorld1 {
    public int countSubstring() {
    String p = "abababa";
    String c = "a";
    int sum = 0;
    int len = p.length();
    for (int i = 0; i < len; i++) {
    if (Character.toString(p.charAt(i)).equals(c)) {
    sum++;
    }
    }
    return sum;
    }
    }