首页 > 编程语言 > 详细

java 基础 - 查找某个字串出现的次数及位置

时间:2018-03-21 12:51:05      阅读:235      评论:0      收藏:0      [点我收藏+]

查找某个字串出现的次数及位置

public class search {
public static void main(String[] args){

String str = "abc123abcd1234";
String searchStr ="bc";
int count = getStrCount(str,searchStr);
System.out.println("count is: "+ count);

}


public static int getStrCount(String str,String searchStr){
int index =0;//define the index
int count =0;//define the count

while((index=str.indexOf(searchStr,index))!= -1) {

if (searchStr.equals(str.substring(index,index+searchStr.length()))) {

System.out.println("index is :" + index);//print index

index = index + searchStr.length();

count++;

}
}
return count;
}

}

 

运行结果:

index is :1
index is :7
count is: 2

 

java 基础 - 查找某个字串出现的次数及位置

原文:https://www.cnblogs.com/yuanchunli/p/8615964.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!