package day15;
/**
* @author QITM
* @date 2020/5/15 21:31
* @描述
* 2.一個子串在整串中出現的次數
* weqerweqtywequiweqopweq
* 思路:
* 1.要找的子串是否存在,如果存在獲取出現的位置,這個可以使用index完成
* 2.如果找到了。那麼就記錄出現的位置並在剩餘的字符串中繼續查找該子串
* 而剩餘字符串的起始是出現位置+子串的長度
* 3.以此類推,通過循環查找,如果找不到就是-1.並對每次找到用計數器記錄
*
*/
public class StringTest_2 {
public static void main(String[] args) {
String str = "weqerweqtywequiweqopweq";
String key = "weq";
int count = getKeyStringCount(str, key);
int count2 = getKeyStringCount2(str, key);
System.out.println("count"+count2);
}
private static int getKeyStringCount2(String str, String key) {
// 1.定義計數器
int count = 0;
// 2.定義變量記錄可以出險的位置
int index = 0;
while ((index = str.indexOf(key, index)) != -1) {
index= index + key.length() + 1;
count++;
}
return count;
}
/**
* 獲取子串在整串出現的次數
* @param str
* @param key
* @return
*/
private static int getKeyStringCount(String str, String key) {
// 1.定義計數器
int count = 0;
// 2.定義變量記錄可以出險的位置
int index = 0;
System.out.println(str.indexOf(key));
while ((index = str.indexOf(key)) != -1) {
str = str.substring(index + key.length());
count++;
}
return count;
}
}