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; }