Java利用正则表达式统计某个字符串出现的次数

时间:2023-03-09 05:05:35
Java利用正则表达式统计某个字符串出现的次数
  1. //统计某个字符出现的次数
  2. private void countSubString(){
  3. String string1="香蕉、玉米、面粉";
  4. String string2="香蕉、玉米、面粉";
  5. String string3="牛奶、鸡蛋";
  6. StringBuffer stringBuffer=new StringBuffer();
  7. stringBuffer.append(string1).append("、").append(string2).append("、").append(string3).append("、");
  8. String totalString=stringBuffer.toString();
  9. System.out.println("组拼后的字符串为:"+totalString);
  10. while (totalString.length()>0) {
  11. //得到第一个字符串比如"香蕉、"
  12. int index=totalString.indexOf("、");
  13. String foodName=totalString.substring(0,index+1);
  14. Pattern pattern = Pattern.compile(foodName);
  15. Matcher matcher = pattern.matcher(totalString);
  16. int count=0;
  17. while(matcher.find()){
  18. count++;
  19. }
  20. totalString= totalString.replaceAll(foodName, "");
  21. System.out.println("食品名字为:"+foodName+",出现次数为:"+count);
  22. System.out.println("统计删除后字符串为:totalString="+totalString);
  23. System.out.println("===============================");
  24. }
  25. }