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;
}
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短