java字符串比较获取字符串出现次数的示例
时间:2022-03-22 16:05:39
比如:javascriptjavasejavaeejavame
思路:
定义一个计数器
获取java第一次出现的位置
从第一次出现位置后剩余的字符串中继续获取java出现的位置每获取一次就计数一次
当获取不到时,计数完成
class StringCount{
public static void main(String[] args){
String s = "javascriptjavasejavaeejavame";
int count = getSubString(s,"java");
System.out.println(count);
}
public static int getSubString(String str,String key){
int count = 0;
int index = 0;
while((index=str.indexOf(key,index))!=-1){
index = index+key.length();
count++;
}
return count;
}
}
第二种方式:
public static int getSubCount_2(String str,String key){
int count = 0;
int index = 0;
while ((index=str.indexOf(key,index))!=-1){
str = str.subtring(index+key.length());
count++;
}
return count;
}
标签:字符串比较
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
详解Spring的StringUtils踩坑记录
2021-08-23 16:14:39
C#的Excel导入、导出
2023-09-10 01:00:24
![](https://img.aspxhome.com/file/2023/7/74827_0s.png)
maven打包时候修改包名称带上git版本号和打包时间方式
2022-03-09 20:51:39
![](https://img.aspxhome.com/file/2023/4/67684_0s.png)
MyBatis-Plus解决逻辑删除与唯一索引的问题
2022-09-09 00:17:03
![](https://img.aspxhome.com/file/2023/4/76274_0s.png)
C++实现图书管理系统
2023-11-03 03:00:35
Spring Boot 集成 Sharding-JDBC + Mybatis-Plus 实现分库分表功能
2023-08-28 16:52:09
![](https://img.aspxhome.com/file/2023/7/58277_0s.jpg)
grails不能运行fork模式解决方法
2023-05-17 18:37:59
C#实现DataTable映射成Model的方法(附源码)
2023-03-12 06:10:56
java如何实现自动生成数据库设计文档
2023-08-07 19:01:28
![](https://img.aspxhome.com/file/2023/3/61323_0s.jpg)
idea 与 maven 使用过程中遇到的问题及解决方案
2021-10-07 02:34:24
![](https://img.aspxhome.com/file/2023/9/69119_0s.png)
SpringCloud分布式链路追踪组件Sleuth配置详解
2023-11-28 23:58:42
![](https://img.aspxhome.com/file/2023/6/60666_0s.png)
Java实现特定范围的完数输出算法示例
2023-11-29 00:43:45
![](https://img.aspxhome.com/file/2023/3/60163_0s.jpg)
C#异步调用实例小结
2023-07-16 10:31:03
mybatis中批量插入的两种方式(高效插入)
2023-09-16 22:21:07
Spring Boot @Conditional注解用法示例介绍
2023-04-18 22:51:51
java线程池ThreadPoolExecutor的八种拒绝策略示例详解
2021-06-24 11:31:10
![](https://img.aspxhome.com/file/2023/0/64390_0s.png)
@valid 无法触发BindingResult的解决
2023-08-10 09:16:12
springboot嵌套子类使用方式—前端与后台开发的注意事项
2023-09-16 12:37:22
Spring Boot2如何构建可部署的war包
2023-11-29 06:40:59
![](https://img.aspxhome.com/file/2023/5/60365_0s.png)
解决问题:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources
2023-11-23 23:40:39
![](https://img.aspxhome.com/file/2023/1/59871_0s.jpg)