1. 程式人生 > >查詢一個字串中包含有幾個指定字串的數量

查詢一個字串中包含有幾個指定字串的數量

public class test{
	public static void main(String[] args){
 		String str = "abcguddcabddgudddgudd";  
	        String s = "gudd";   // 指定的字串
	        int count = 0;  // 初始值
	        //一共有str.length()的迴圈次數  
	        for(int i=0; i<str.length() ; ){  
	            int c = -1;  
	            c = str.indexOf(s);  
	            //如果有S這樣的子串。則C的值不是-1.  
	            if(c != -1){  // 如果c=-1則說明不在在
		    //這裡的c+1 而不是 c+ s.length();這是因為。如果str的字串是“aaaa”, s = “aa”,則結果是2個。但是實際上是3個子字串  
	            //將剩下的字元沖洗取出放到str中  
	                 str = str.substring(c + 1);  // 從存在的那個下標後一位開始
	                 count ++;  
	                 System.out.println(str);  
	            }else { 
	                System.out.println("沒有了");  
	                break;  
	            }  
	        }  
	        System.out.println("存在"+count+"個"); 
	}
}

輸出結果:

uddcabddgudddgudd
udddgudd
udd
沒有了
存在3個