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.           
  11.         while (totalString.length()>0) {  
  12.             //得到第一个字符串比如"香蕉、"  
  13.             int index=totalString.indexOf("、");  
  14.             String foodName=totalString.substring(0,index+1);  
  15.               
  16.             Pattern pattern = Pattern.compile(foodName);    
  17.             Matcher matcher = pattern.matcher(totalString);    
  18.             int count=0;  
  19.             while(matcher.find()){  
  20.                 count++;  
  21.             }  
  22.             totalString= totalString.replaceAll(foodName, "");  
  23.             System.out.println("食品名字为:"+foodName+",出现次数为:"+count);  
  24.             System.out.println("统计删除后字符串为:totalString="+totalString);  
  25.             System.out.println("===============================");  
  26.         }  
  27.     } 
原文地址:https://www.cnblogs.com/zhwl/p/3632133.html