//要求:计算字符串中子串出现的次数。例如字符串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次 

解决方案 »

  1.   

    java 正则方式: Pattern p;
    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…… 这样的组合,结果也同样全是空串。
      

  2.   

    split("xxx");是切割字符串的函数。
      

  3.   

    String target = "abdeacdsdfsdfacddfsfdsacd"
    String selectStr ="acd"
    count = target.length() - targetStr.replaceAll(selectStr, "").length())/ selectStr.length()
      

  4.   

    import java.util.regex.Matcher;
    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);
    }}
      

  5.   

    楼上说的都很详细了,用split()括号中的参数是分割字符串的正则表达式,比如split(" ")就是在字符串中遇到空格分割,但是这个空格是会被去掉的