统计一个子字符串的个数 Java

/**
* 7种方法,统计字符串中“子字符串”的个数;
 */

public class CountSonStr {


public static void main(String[] args) {
String s = "1aaaa1aaa1aa1a";
String s1 = "aaa";
// System.out.println(count(s, s1));
}

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;
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值