public class Match { public static void main(String[] args) { String str1 = "addddchenjkkkkkchenkkkkklchenkkkchenllll"; String str2 = "chen"; int match = 0; if (str1.lastIndexOf(str2) == (str1.length() - str2.length())) { match = str1.split(str2).length; } else { match = str1.split(str2).length - 1; } System.out.println("====" + match); }} 测试下
public class a { public static void main(String[] args) { String a = "12345464567575623412343"; String b = "23"; String c = a.replace(b, ""); int time = (a.length() - c.length())/b.length(); System.out.println(time); }}
Apache Jakarta Commons Lang 下有个 StringUtil.countMatches() 方法,可以直接进行计数。这个包很可能就在你导入的其他框架的 jar 中含有的。StringUtil 类中含有很多很多有用的 String 方法。Jakarta Commons Lang 的官方下载地址: http://commons.apache.org/downloads/download_lang.cgi
应该可以得到str1在str2中出现的次数!
public static void main(String[] args) {
String str1 = "addddchenjkkkkkchenkkkkklchenkkkchenllll";
String str2 = "chen";
int match = 0;
if (str1.lastIndexOf(str2) == (str1.length() - str2.length())) {
match = str1.split(str2).length;
} else { match = str1.split(str2).length - 1;
}
System.out.println("====" + match);
}}
测试下
public class a {
public static void main(String[] args) {
String a = "12345464567575623412343";
String b = "23";
String c = a.replace(b, "");
int time = (a.length() - c.length())/b.length();
System.out.println(time);
}}
http://commons.apache.org/downloads/download_lang.cgi