java查找字符串里与指定字符串相同的个数

时间:2021-08-23 15:16:32
public class EmployeeDemo {
//方法一:
public int search(String str,String strRes) {//查找字符串里与指定字符串相同的个数
int n=0;//计数器
// for(int i = 0;i<str.length();i++) {
//
// }
while(str.indexOf(strRes)!=-1) {
int i = str.indexOf(strRes);
n++;
str = str.substring(i+1);
}
return n;
}
//方法二:
public int search2(String str,String strRes) {
int n = 0;//计数器
int index = 0;//指定字符的长度
index = str.indexOf(strRes);
while(index!=-1) {
n++;
index = str.indexOf(strRes,index+1);
} return n;
}
public static void main(String []args) {
String arr = "朋友啊朋友,你现在怎么样?";
EmployeeDemo emp = new EmployeeDemo();
System.out.println(emp.search(arr, "朋友"));
System.out.println(emp.search2(arr, "朋友"));
}
}