a、大串中查找子串出现的次数
public class SubStringDemo {
public static void main(String[] args) {
// 查找字串在大串中出现的次数
String str = "hanbasdnbafllgnbahjnbakqqqqlnbaxnbai";
String regex = "nba";
// 方式1
int count = getCount1(str, regex);
// 方式2
int count2 = getCount2(str, regex);
System.out.println(count);
System.out.println(count2);
}
/*
* 方式2: 不截取字符串,逐渐缩小查找范围
*/
private static int getCount2(String str, String regex) {
// 定义统计变量
int count = 0;
// 定义子串在大串中第一次出现的索引
int index = 0;
// 从每次找到的小串后,开始下一次查找
while ((index = str.indexOf(regex, index)) != -1) {
// 如果找到小串,下一次开始查找的起始索引是小串出现的索引+小串的长度
index = index + regex.length();
// 统计变量++
count++;
}
return count;
}
/*
* 方式1:查找到小串后将已经查询的部分截取掉。
* 返回值:统计变量的值 int
* 参数列表:大串和小串
* 注:这种方式会在常量池产生很多截取出来的字符串数据,浪费内存
*/
public static int getCount1(String maxString, String minString) {
// 定义统计变量
int count = 0;
// 定义小串在大串中第一次出现的索引
int index = 0;
// 查找赋值并判断,如果返回值不是-1,说明小串在大串中是存在的。
while ((index = maxString.indexOf(minString)) != -1) {
// 统计变量++
count++;
// 把查找过的数据给截取掉,重新赋值给大串
maxString = maxString.substring(index + minString.length());
}
return count;
}
}
b、打印出字符串"abbbbbccccdddee"中每个字符出现的次数,要求输出格式:“a(1)b(5)c(4)d(3)e(2)”,并将结果写入文件。
public class Test5 {
public static void main(String[] args) throws IOException {
// 1,定义一个需要被统计字符的字符串
String s = "abbbbbccccdddee";
// 2,将字符串转换为字符数组
char[] arr = s.toCharArray();
// 3,定义双列集合,存储字符串中字符以及字符出现的次数
TreeMap<Character, Integer> map = new TreeMap<>();
// 4,遍历字符数组获取每一个字符,并将字符存储在双列集合中
for (char c : arr) {
// 5,存储过程中要做判断,如果集合中不包含这个键,就将该字符当作键,值为1存储,如果集合中包含这个键,就将值加1存储
if (!map.containsKey(c)) { // 如果不包含这个键
map.put(c, 1);
} else {
map.put(c, map.get(c) + 1);
}
}
// 6,遍历集合将键和值拼接起来
StringBuilder sb = new StringBuilder();
for (Character key : map.keySet()) { // hm.keySet()代表所有键的集合
sb.append(key + "(" + map.get(key) + ")");
}
// 输出结果
System.out.println(sb);
// 创建输出流对象写入文件
BufferedWriter bw = new BufferedWriter(new FileWriter("result.txt"));
bw.write(sb.toString());
bw.close();
}
}