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 妈妈生日祝福语简短励志