在一个字符串查找有几个子串?

1、题目要求
:在这个字符串中"klfjsdfwofjwokzljwo" 有多少个wo字?

方法一:最笨的方法

//	定义字符串
	String str="klfjsdfwofjwokzljwo";
		//	定义子串
	String sub="wo";
		//	indexOf(String str)返回字符串第一次出现的索引
	int index=str.indexOf(sub);
	System.out.println(index);
		//	第一次出现在索引7,则第二次从索引9(index+sub.length())开始
	index=str.indexOf(sub,index+sub.length());
	System.out.println(index);
		//	同上
	index=str.indexOf(sub,index+sub.length());
	System.out.println(index);
}

方法二:while循环,每次下标值自动加子串的长度

//	定义字符串
		String str="klfjsdfwofjwokzljwo";
			//	定义子串
		String sub="wo";
			//	通过循环来计算索引出现的次数来得到结果
		int count=0;	//	计数器初始为0
		int index=0;	//	下标初始我0
	//	判断首次在字符串是否能找到子串,有就使计数器+1,下标值自动+sub.length
		while ((index=str.indexOf(sub,index))!=-1) {
			count++;
			index=index+sub.length();
		}
			System.out.println(count);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值