一、题目描述
给定两个任意字符串,获取一个字符串在另一个字符串中出现的次数,比如“ab”在“abcdeabdeabababdab”中出现的次数
二、解题思路
- 方式一:使用String的indexOf(String str) 方法遍历寻找并记录子字符串在目标字符串中首次出现的位置,并存入index变量中,然后使用String的substring() 方法从 (index + 子字符串的长度)位置 开始截取目标字符串到最后一个字符。直到indexOf(String str)方法返回 -1 ,即无法从目标字符串中找到待匹配的子字符串时,结束循环。
- 方式二:通过String的indexOf(String str,int fromIndex)方法,来遍历寻找子字符串在目标字符串中出现的次数,每当找到一次子字符串,就让 fromIndex 加上 子字符串的长度。直到indexOf(String str,int fromIndex)方法返回 -1 ,即无法从目标字符串中找到待匹配的子字符串时,结束循环。
- 说明:index 在每次找到子字符串后都要加上 子字符串的长度 的原因是为了从已经找到的子字符串的后边接着去寻找,防止发生重复寻找。
三、代码示例
package com.commonclass.exercise02;
import org.junit.Test;
/**
* @ClassName StringDemo02
* @Description 获取一个字符串在另一个字符串中出现的次数,比如“ab”在“abcdeabdeabababdab”中出现的次数
* @Author wk
* @Date 2021/12/9 20:00
* @Version 1.0
*/
public class StringDemo02 {
public int getCount(String mainStr, String subStr) {
int mainLength = mainStr.length();
int subLength = subStr.length();
int count = 0;
int index = 0;
if (mainLength >= subLength) {
// 方式一
// while ((index = mainStr.indexOf(subStr)) != -1) {
// count++;
// mainStr = mainStr.substring(index + subStr.length());
// }
// 方式二
while((index = mainStr.indexOf(subStr,index)) != -1){
count++;
index += subLength;
}
return count;
} else {
return 0;
}
}
@Test
public void test() {
String str1 = "AB";
String str2 = "ABABABCDEFFABABDDDDEEEEFFFAAAAA";
int count = getCount(str2,str1);
System.out.println(count); // count = 5
}
}
四、测评结果
- 测评用例:
String str1 = "AB";
String str2 = "ABABABCDEFFABABDDDDEEEEFFFAAAAA";