Java计算字符串中子字符串或字符的出现
示例
countMatchesorg.apache.commons.lang3.StringUtils中的方法通常用于计算:中子字符串或字符的出现次数String:
import org.apache.commons.lang3.StringUtils; String text = "One fish, two fish, red fish, blue fish"; //计算子串的出现 String stringTarget = "fish"; int stringOccurrences = StringUtils.countMatches(text, stringTarget); //4 //计算一个字符的出现 char charTarget = ','; int charOccurrences = StringUtils.countMatches(text, charTarget); //3
否则,对于与标准JavaAPI相同的操作,您可以使用正则表达式:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
String text = "One fish, two fish, red fish, blue fish";
System.out.println(countStringInString("fish", text)); //版画4
System.out.println(countStringInString(",", text)); //版画3
public static int countStringInString(String search, String text) {
Pattern pattern = Pattern.compile(search);
Matcher matcher = pattern.matcher(text);
int stringOccurrences = 0;
while (matcher.find()) {
stringOccurrences++;
}
return stringOccurrences;
}
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短