<span style="font-size:18px;">package com.liang;
//【程序49】
//题目:计算字符串中子串出现的次数
public class Demo49 {
public static void main(String[] args) {
String str = "erbcedebctbcyubcedebciopfbbcedecghbcjklbcbcede";
int count = 0;
// 方法一:
// char[] array = str.toCharArray();
// for (int i = 0; i < array.length; i++) {
// if (array[i] == 'b' && array[i + 1] == 'c') {
// count++;
// }
// }
// System.out.println(count);
// 方法二:
String str1 = "bcede";
// for (int i = 0; i <= str.length() - str1.length(); i++) {
// String temp = str.substring(i, i + str1.length());
// if (temp.equals(str1)) {
// count++;
// }
// }
// System.out.println(count);
// 方法三://比方法二更严谨一点,可以让系统少判断几次
char t = str1.charAt(0);
for (int i = 0; i <= str.length() - str1.length(); i++) {
if (str.charAt(i) == t) {
String temp = str.substring(i, i + str1.length());
if (temp.equals(str1)) {
count++;
}
}
}
System.out.println(count);
}
}
</span>
题目:计算字符串中子串出现的次数
最新推荐文章于 2023-01-05 16:39:13 发布