最近面试遇到的一个基础题
/**
* 统计一个字符串出现在另一个字符串中的次数
*
*/
public class CountStringTest {
/**
* @param o 被统计的字符串
* @param c 需要统计的字符串
* @return 出现的次数
*/
public static int startCount(String o, String c) {
// 按照需要统计的字符串切割
String[] splitStr = o.split(c);
StringBuilder sb = new StringBuilder();
// 可以打印查看切割后的字符串(非必须)
for(String s : splitStr) {
System.out.println(s);
// 附加,统计并去除出现的字符串,一:使用StringBuilder
sb.append(s);
}
int count;
// 如果这个字符串的结尾刚好是统计的字符串,则次数为切割的数组长度
if (o.endsWith(c)) {
count = splitStr.length;
} else { // 否则为数组长度-1
count = splitStr.length - 1;
}
// 将新字符串赋值给原字符串
o = sb.toString();
// 查看结果
System.out.println("统计后的字符串:" + o);
// 返回出现的次数
return count;
}
/**
* main方法测试
* @param args
*/
public static void main(String[] args) {
String o = "ababcababcdabcabcdeabcababc";
String c = "abc";
int startCount = startCount(o, c);
System.out.println(startCount);
}
}
结果:
ab
ab
d
de
ab
统计后的字符串:ababddeab
6