统计一个字符串在另一个字符串中出现的次数(并将其去除)

最近面试遇到的一个基础题

/**
 * 统计一个字符串出现在另一个字符串中的次数
 *
 */
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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值