判断字符串中是否包含某字符子串

 

方法一:不断截取源字符串

 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+ "中含有 "+total+ "个 "+str2);

方式二,字符串转数组

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  

 

posted @ 2019-11-08 20:36  高少侠也在江湖  阅读(3320)  评论(0编辑  收藏  举报