Java利用正則表達式統計某個字符串出現的次數


  • //統計某個字符出現的次數  
  •     private void countSubString(){  
  •         String string1="香蕉、玉米、面粉";  
  •         String string2="香蕉、玉米、面粉";  
  •         String string3="牛奶、雞蛋";  
  •         StringBuffer stringBuffer=new StringBuffer();  
  •         stringBuffer.append(string1).append("、").append(string2).append("、").append(string3).append("、");  
  •         String totalString=stringBuffer.toString();  
  •         System.out.println("組拼后的字符串為:"+totalString);  
  •           
  •         while (totalString.length()>0) {  
  •             //得到第一個字符串比如"香蕉、"  
  •             int index=totalString.indexOf("、");  
  •             String foodName=totalString.substring(0,index+1);  
  •               
  •             Pattern pattern = Pattern.compile(foodName);    
  •             Matcher matcher = pattern.matcher(totalString);    
  •             int count=0;  
  •             while(matcher.find()){  
  •                 count++;  
  •             }  
  •             totalString= totalString.replaceAll(foodName, "");  
  •             System.out.println("食品名字為:"+foodName+",出現次數為:"+count);  
  •             System.out.println("統計刪除后字符串為:totalString="+totalString);  
  •             System.out.println("===============================");  
  •         }  
  •     } 

  • 免責聲明!

    本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



     
    粵ICP備18138465號   © 2018-2025 CODEPRJ.COM