//要求:计算字符串中子串出现的次数。例如字符串abdeacdsdfsdfacddfsfdsacd中,字符串acd出现了3次
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str=input.next();
String []strs=str.split("acd");
if(str.endsWith("acd"))
{
int i=strs.length;
System.out.println("字符串acd出现了"+i+"次"); }
else
{
System.out.println("字符串acd出现了"+(strs.length-1)+"次");
}
}
//bug:输入acd或者acdacdacd的话输出是0次
public static void main(String[] args)
{
Scanner input=new Scanner(System.in);
System.out.println("请输入一个字符串:");
String str=input.next();
String []strs=str.split("acd");
if(str.endsWith("acd"))
{
int i=strs.length;
System.out.println("字符串acd出现了"+i+"次"); }
else
{
System.out.println("字符串acd出现了"+(strs.length-1)+"次");
}
}
//bug:输入acd或者acdacdacd的话输出是0次
Matcher m ; p = Pattern.compile("acd");
m = p.matcher(str); int num=0;
while(m.find()){num++;}
System.out.println(num);
你的代码出现问题主要原因在于 split("xxx") 的时候, 会把 原来字符串中的 xxx都给过滤掉,也就是说 一个字符串str="123acd321", 那么str.split("acd")={"123","321"},所以 如果是 str=“acd”的话,split(“acd”)之后 就成了一个空串,所以结果是 0 , 同样 如果全是 acdacdacd…… 这样的组合,结果也同样全是空串。
String selectStr ="acd"
count = target.length() - targetStr.replaceAll(selectStr, "").length())/ selectStr.length()
import java.util.regex.Pattern;
public class StringTest { /**
* 通过java正则表达式计算
* 字符串中出现指定子串的
* 数量
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int count=0;
String str = "acdeacdsdfsdfacddfsfdsacd";
Pattern p;
Matcher m;
p = Pattern.compile("acd");
m = p.matcher(str);
while(m.find()){
count++;
}
System.out.println(count);
}}