Determining if a certain character string substring

 

Method a: continuously taken source string

 1 String  str1  =  "nihaokogaokoshaokoxia "; 
 2 String  str2  =  "oko "; 
 3 int  total  =  0; 
 4 for  (String  tmp  =  str1;  tmp  !=  null&&tmp.length()> =str2.length();){ 
 5   if(tmp.indexOf(str2)  ==  0){ 
 6     total  ++; 
 7     tmp  =  tmp.substring(str2.length()); 
 8   }else{ 
 9     tmp  =  tmp.substring(1); 
10   } 
11 } 
12 System.out.println (str1 + "contain" + total + "a" + str2);

Second way, an array of strings turn

1 String  str1  =  "nihaoksdoksad "; 
2 char  []c=str1.toCharArray(); 
3 int  total=0; 
4 for(int  i=0;i <c.length-1;i++) 
5 if(c[i]== 'o '&&c[i+1]== 'k ') 
6 total++; 
7 System.out.println(str1+ "中含有 "+total+ "个ok ");
8  

 

Guess you like

Origin www.cnblogs.com/gf-jie/p/11823133.html