1.键盘录入一个大字符串,再录入一个小字符串
2.统计小字符串在大字符串中出现的次数
3.代码运行打印格式:
请输入大字符串:woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma
请输入小字符串:heima
控制台输出:小字符串heima,在大字符串中共出现3次
public class Exam03 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = "woaiheima,heimabutongyubaima,wulunheimahaishibaima,zhaodaogongzuojiushihaoma";
String sub = "heima";
int filter = filter(s, sub);
System.out.println(sub+"在大字符串中出现了"+filter+"次");
}
public static int filter(String s,String sub){
int old_length=s.length();
String replace="";
if (s.contains(sub)){
replace = s.replace(sub, "");//将需要查找的字符串替换为空
}
int new_length= replace.length();//用原来字符串的长度去减替换过的字符串就是该字符串中字符出现的次数
int count=(old_length-new_length)/(sub.length());//因为是字符串中字符出现的次数,所以要除以字符串你的长度最后就是字符串在另一个字符串中出现的次数
return count;
}
}
此方法跟前面统计字符串中每个字符出现的个数大致相同,如果想保留原来的字符串就在方法体首部将原来的字符串赋给一个中间变量.统计完再将他赋值回去.
下面的方法是利用了String里面的indexOf方法.通过判断返回的值不等于-1开始循环.indexOf是返回指定字符串在原来的字符串出现第一次的位置索引.然后下次循环就从这一次的下一次开始循环.每次得到索引值时计数器加一.
/**
* .获取一个字符在一个字符串中出现的次数,
* 比如:String st = "adfdfsfksdfsdjfhsjdfhsfkdfgjdfkgljlds";
* 字符‘f’在字符串st中出现的次数
*/
public class Assign03 {
public static void main(String[] args) {
String st = "adfdfsfksdfsdjfhsjdfhsfkdfgjdfkgljlds";
int count=pinrtCount(st, "f");
System.out.println("出现了"+count+"次");
}
public static int pinrtCount(String string, String subString) {
int index=0;
int count=0;
while ((index = string.indexOf(subString,index)) !=-1){
//在循环控制的条件中将获得的索引值赋给index,不等于-1是因为.在JDK中规定了indexOf查找不到子字符串时就返回-1.在我们这里也就是跳出循环的意思
index++;//得到索引后,从本位置开始进行下一次循环,所以字符串的索引加一
count++;//计数器统计出现的次数
}
return count;
}
}
下面是我们老师教的方法.可以自行参考.方法不在多,自己掌握就好.
public class Test {
public static void main(String[] args) {
String str1 = "aaaa";
String str2 = "aa";
int count=0;
while (true) {
int index = str1.indexOf(str2);//0
if (index != -1) {
count++;
// str1 = str1.substring(index+str2.length()); //每次截取不包含出现过的字符
str1 = str1.substring(index+1);//一个一个字符往后计算
} else {
break;
}
}
System.out.println(count);
}
public static void ss(String str1, String str2) {
int count = 0;
while (true) {
int i = str1.indexOf(str2);
if (i == -1) {
break;
} else {
count++;
str1 = str1.substring(i+str2.length());
}
}
System.out.println(count);
}
}