public class A {
/**
* 7种方法,统计字符串中“子字符串”的个数;
*/
public static void main(String[] args) {
String s = "1aaaa1aaa1aa1a";
String s1 = "aaa";
// System.out.println(count(s,"aa"));
}
public static int count1(String s, String str) {
int k = 0;
for (int index = 0;; index += str.length()) {
index = s.indexOf(str, index);
if (index == -1)
break;
k++;
}
System.out.println(k);
return k;
}
public static int count2(String s, String s1) {
int i = 1, count = 0;
while (i < s.length() - (s1.length() - 1)) {
if ((s.substring(i, i + s1.length()).equals(s1))) {
count++;
i += s1.length();
} else {
i++;
子字符串是什么}
}
return count;
}
public static int count3(String s, String sub) {
int sum = 0;
String[] s1;
s1 = s.split(sub);
sum = s1.length;
return sum;
}
public static int count4(String s, String sub) {
int k = 0;
for (int i = 0; i < s.length(); i++) {
if (s.substring(i, s.length()).startsWith(sub)) {
k++;
i += sub.length() - 1;
}
}
return k;
}
public static int count5(String s, String sub) {
int k = 0;
while (true) {
int n = s.indexOf(sub);
if (n >= 0) {
k++;
s = s.substring(n + sub.length());
} else {
break;
}
}
return k;
}
public static int count6(String s, String sub) {
int num = 0;
int beginIndex = 0;
int endIndex;
String temp;
for (;;) {
endIndex = beginIndex + sub.length();
if (endIndex >= s.length() + 1) {
break;
}
temp = s.substring(beginIndex, endIndex);
if (sub.equals(temp)) {
num++;
beginIndex = endIndex;
} else {
beginIndex++;
}
}
return num;
}
private static int count7(String s, String sub) { int n = 0;
for (int i = 0; i < s.length(); i++) {
int j;
for (j = 0; j < sub.length(); j++) {
if (s.charAt(i) != sub.charAt(j)) {
break;
} else {
if (i + 1 == s.length()) {
break;
}
i++;
}
}
if (j == sub.length()) {
i--;
n++;
}
}
return n;
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。