package cn.itcast;
public class StringDemo4 {
/*
* 大串中查找字串出现的次数
*/
public static void main(String[] args) {
String max = "nbaernbatynbauinbaopnbasfdg";
String min = "nba";
// int count = getKeyStringCount(str,key);
int count = getKeyStringCount_2(max, min);
System.out.println("count=" + count);
}
// 第二种方式。不会在字符串常量池中产生很多字符串。(建议使用该种方式)
/**
* 获取子串在大串中出现的次数。
* @param max
* @param min
* @return
*/
public static int getKeyStringCount_2(String max, String min) {
// 1,定义计数器。
int count = 0;
// 2,定义变量记录key出现的位置。
int index = 0;
while ((index = max.indexOf(min, index)) != -1) {
index = index + min.length();
count++;
}
return count;
}
/**
* 获取子串在整串中出现的次数。
*
* @param str
* @param key
* @return
*/
// 第一种方式。会在字符串常量池中产生很多字符串。
public static int getKeyStringCount(String str, String key) {
// 1,定义计数器。
int count = 0;
// 2,定义变量记录key出现的位置。
int index = 0;
while ((index = str.indexOf(key)) != -1) {
str = str.substring(index + key.length());
count++;
}
return count;
}
}
|
|