代码如下~
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();
}//为什么在运行时不能实现调用?
请高手指教
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();
}//为什么在运行时不能实现调用?
请高手指教
其实可以不用循环,这样写:
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;
}
}
没必要这么麻烦 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;
}
}