java字符串出现的位置_Java 获取指定字符串出现的次数及第N次出现的位置

Java中 获取指定字符串在另一个字符串中出现的次数

方式一

/**

* @param args

*/

public static void main(String[] args) {

String srcText = "Hello World";

String findText = "e";

int num = appearNumber(srcText, findText);

System.out.println(num);

}

/**

* 获取指定字符串出现的次数

*

* @param srcText 源字符串

* @param findText 要查找的字符串

* @return

*/

public static int appearNumber(String srcText, String findText) {

int count = 0;

Pattern p = Pattern.compile(findText);

Matcher m = p.matcher(srcText);

while (m.find()) {

count++;

}

return count;

}

方法二

/**

* @param args

*/

public static void main(String[] args) {

String srcText = "Hello World";

String findText = "e";

int num = appearNumber(srcText, findText);

System.out.println(num);

}

/**

* public int indexOf(int ch, int fromIndex)

* 返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索

*

* @param srcText

* @param findText

* @return

*/

public static int appearNumber(String srcText, String findText) {

int count = 0;

int index = 0;

while ((index = srcText.indexOf(findText, index)) != -1) {

index = index + findText.length();

count++;

}

return count;

}

获取第N次出现时的位置

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class Demo {

//判断"Ab2Ad3A4"中"A"出现第二次的位置

public static void main(String[] args) {

String str = "Ab2Ad3A4";

Pattern pattern = Pattern.compile("A");

Matcher findMatcher = pattern.matcher(str);

int number = 0;

while(findMatcher.find()) {

number++;

if(number == 2){//当“A”第二次出现时停止

break;

}

}

int i = findMatcher.start();//“A”第二次出现的位置

System.out.println("'A'第二次出现的位置是:"+i);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值