博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java小练习--获取abc字符串在整个字符串中出现的次数
阅读量:4326 次
发布时间:2019-06-06

本文共 864 字,大约阅读时间需要 2 分钟。

在下面一行字符串中获取abc字符串在整个字符串中出现的次数。

"wabcerabctyabcuiabcabcqq"

思路:使用indexOf和substring();

源码如下:

public static void main(String[] args) 	{		String s1 = "abcwabcerabctyabcuiabcabc";		String s2 = "abc";		int count = getCount(s1,s2);		int count2 = getCount2(s1,s2);		System.out.println("count = "+count);		System.out.println("count2 = "+count2);	}	/*第一种方法	获取abc字符串在整个字符串中出现的次数。	"wabcerabctyabcuiabcabcqq"	*/	public static int getCount(String str,String sub)	{		int index = 0;		int count = 0;		while((index = str.indexOf(sub,index))!=-1)		{				index = index + sub.length();			count++;		}		return count;	}          /*第二种方法*/	public static int getCount2(String str,String sub)	{		int index = 0;		int count = 0;		while((index=str.indexOf(sub))!=-1)		{			str = str.substring(index+sub.length());			count++;		}		return count;	}}

 

 

转载于:https://www.cnblogs.com/pangblog/p/3320173.html

你可能感兴趣的文章
thinkphp3.2.3 bug集锦
查看>>
[BZOJ 4010] 菜肴制作
查看>>
C# 创建 读取 更新 XML文件
查看>>
KD树
查看>>
VsVim - Shortcut Key (快捷键)
查看>>
C++练习 | 模板与泛式编程练习(1)
查看>>
HDU5447 Good Numbers
查看>>
08.CXF发布WebService(Java项目)
查看>>
java-集合框架
查看>>
RTMP
查看>>
求一个数的整数次方
查看>>
点云PCL中小细节
查看>>
铁路信号基础
查看>>
RobotFramework自动化2-自定义关键字
查看>>
[置顶] 【cocos2d-x入门实战】微信飞机大战之三:飞机要起飞了
查看>>
BABOK - 需求分析(Requirements Analysis)概述
查看>>
第43条:掌握GCD及操作队列的使用时机
查看>>
Windows autoKeras的下载与安装连接
查看>>
CMU Bomblab 答案
查看>>
微信支付之异步通知签名错误
查看>>