Java > Recursion-1 > strCount (CodingBat Solution)

Problem:

Given a string and a non-empty substring sub, compute recursively the number of times that sub appears in the string, without the sub strings overlapping.

strCount("catcowcat", "cat") → 2
strCount("catcowcat", "cow") → 1
strCount("catcowcat", "dog") → 0


Solution:

public int strCount(String str, String sub) {
  int strlen = str.length();
  int sublen = sub.length();
  if (strlen < sublen) return 0;
  if (str.substring(0,sublen).equals(sub))
    return 1 + strCount(str.substring(sublen), sub);
  else 
    return strCount(str.substring(1), sub);
}


6 comments :

  1. if (!str.contains(sub)) return 0;
    else return 1 + strCount(str.substring(str.indexOf(sub)+sub.length()), sub);

    ReplyDelete
    Replies
    1. If we're going to use any old java.lang.string method, might as well defeat the purpose of this exercise entirely and not even bother with recursion:

      String s=str.replace(sub,"");
      return (str.length()-s.length())/sub.length();

      Delete
  2. public int strCount(String str, String sub) {
    if(str.indexOf(sub)==-1) return 0;
    if(str.indexOf(sub)!=-1)
    {
    return 1 + strCount(str.substring(str.indexOf(sub)+sub.length()), sub);
    }
    return 0;
    }

    ReplyDelete
  3. if(str.equals("")) return 0;
    if(str.startsWith(sub)) return 1 + strCount(str.substring(sub.length()), sub);
    return strCount(str.substring(1), sub);

    ReplyDelete
  4. public int strCount(String str, String sub) {
    if(str.isEmpty()){
    return 0;
    }
    if(str.startsWith(sub)){
    return 1 + strCount(str.substring(sub.length()), sub);
    }
    return strCount(str.substring(1), sub);
    }

    ReplyDelete
  5. public int strCount(String str, String sub) {
    if(str.isEmpty()){
    return 0;
    }
    return (str.startsWith(sub))?
    1 + strCount(str.substring(sub.length()), sub)
    : strCount(str.substring(1), sub);
    }

    ReplyDelete

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact