0
点赞
收藏
分享

微信扫一扫

java小工具util系列2:获取字符modelStr在字符串str中第count次出现时的下标


java小工具util系列2:获取字符modelStr在字符串str中第count次出现时的下标_java

举例说明

问题:输出字符串 "0,1,61,"的第一个逗号、第二个逗号、第三个逗号、的索引

代码

@Test
public void getCommaIndex() {
String str = "0,1,61,";
String modelStr = ","; //代表要搜索的特定字符串
int count = 3; //代表要搜索的特定字符串出现第几次的索引位置
//对子字符串进行匹配
Matcher slashMatcher = Pattern.compile(modelStr).matcher(str);
int index = 0;
//matcher.find();尝试查找与该模式匹配的输入序列的下一个子序列
while(slashMatcher.find()) {
index++;
//当modelStr字符第count次出现的位置
if(index == count){
break;
}
}
//matcher.start();返回以前匹配的初始索引。
System.out.println(slashMatcher.start());
}

举报

相关推荐

0 条评论