This article mainly introduces relevant information about Java's method of determining whether a string contains a substring. Here are three methods to help you achieve such a function. Friends in need can refer to it
java Method to determine whether a string contains a substring
Method one:
String str1 = "nihaoksdoksad "; String str2 = "ok "; int total = 0; for (String tmp = str1; tmp != null&&tmp.length()> =str2.length();){ if(tmp.indexOf(str2) == 0){ total ++; } tmp = tmp.substring(1); } System.out.println(str1+ "中含有 "+total+ "个 "+str2);
Method two :
String str1 = "nihaokokosdokosad "; String str2 = "oko "; int total = 0; for (String tmp = str1; tmp != null&&tmp.length()> =str2.length();){ if(tmp.indexOf(str2) == 0){ total ++; tmp = tmp.substring(str2.length()); }else{ tmp = tmp.substring(1); } } System.out.println(str1+ "中含有 "+total+ "个 "+str2);
Method three:
String str1 = "nihaoksdoksad "; char []c=str1.toCharArray(); int total=0; for(int i=0;i <c.length-1;i++) if(c[i]== 'o '&&c[i+1]== 'k ') total++; System.out.println(str1+ "中含有 "+total+ "个ok ");
The above is the detailed content of Example sharing of how to determine whether a string contains a substring in Java. For more information, please follow other related articles on the PHP Chinese website!