给定一个字符串找到子串在字符串中出现的次数。String s = “abcitcastabcxxxabc”中的“abc”
搞了半天感觉我编的有些小bug,怎样能更准确
public static void main(String[] args) {
// 定义字符串
String str = "abcitcastabcxxxabc";
int index = 0;
int count = 0;
int a = str.indexOf("abc", index);
while (a >= 0) {
index = a + 3;
count++;
a = str.indexOf("abc", index);
if (a < 0) {
break;
}
}
System.out.println(count);
}
} |
|