• Register
0 votes

Problem :

I am facing following issue need solution
return true if the string "cat" and "dog" appear the same number of times in the given string
6 5 3
6,930 points

Please log in or register to answer this question.

2 Answers

0 votes

Solution :

Following is my answer. It is working as per need. Hope it helps you.

public boolean catDogString(String str) {
  int cat = 0 ;
  int dog = 0 ;
  for(int s  = 0 ; s < str.length()-2; s++){
    String temp = str.substring(s,s+3);
  return cat==dog?true:false;
9 7 4
38,600 points
0 votes


List of  few critical problems in your code

1. Your call to substring() fetches a string of size 2. That string can never be cat nor dog. Change the second parameter in the               method call to i + 3 to get 3 characters.


2. Your call to substring() will throw an IndexOutOfRangeException, as i approaches the end of the length of the input string.              Make sure you do not ask for a substring that "overflows" the length of the input string. One way to fix this bug, would be to change        the conditional expression in your for loop to i < str.length() - 2.


3. The return value of your method will always be true. In the case where dogAnswer != catAnswer you return exactly that                    expression - which will resolve to true. A possible solution: Merge the two return statements into return dogAnswer ==          catAnswer.

Additionally, there are a few things you could do to make your code simpler:

1. There really is no need to copy cat_Count into catAnswer and dog_Count into dogAnswer. Throw away two of the variables, and        use the other pair exclusively.

Here's an "All Correct" solution that uses split. The -1 is used to preserve trailing empty strings.

int count(String needle, String haystack) {
  return haystack.split(needle, -1).length - 1;

public boolean catDog(String str) {
  return count("dog", str) == count("cat", str);

You will want to iterate each character in your string and then check to see if the substring is equal to either cat or dog and increments the counts.

public boolean catDog(String str) {

  int end = str.length();
  int cDog = 0;
  int cCat = 0;

  // We don't need to go to the end because cat/dog are 3 characters long each. So we can avoid extra checks.
  for (int i=0; i < end-2; i++) {
        if(str.substring(i, i+3).equals("cat")) {
        } else if(str.substring(i, i+3).equals("dog")) {

   return cCat == cDog ? true : false;

A solution with less duplication would be to write a function that counts occurrences of a substring within a string, then call that function with the string and "cat", and with the string and "dog", and return whether the two counts agree.

public boolean catDog(String str) {
    int cdog = 0;
    int ccat = 0;

    for (int i = 0; i < str.length()-2; i++)
        if (str.charAt(i)== 'c' && str.charAt(i+1)== 'a' && str.charAt(i+2)== 't')

        else if(str.charAt(i) == 'd' && str.charAt(i+1)== 'o' && str.charAt(i+2)== 'g')


    if (cdog == ccat)
        return true;

        return false;


10 6 4
31,120 points

Related questions

0 votes
1 answer 6 views
Problem: return true if the string "cat" and "dog" appear the same number of times in the given string.
asked Feb 23 Muneeb Saadii 4.2k points
0 votes
1 answer 168 views
Problem : I am trying to print every string in Reverse Double Character way (e.g. string -> ggnniirrttss) import java.util.Scanner; public class ReverseDoubleCharecters { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("Enter ... I get as follows: ss tt rr ii nn gg All double characters are printed on new lines. Anybody has the solution on this?
asked Nov 22, 2019 peterlaw 6.9k points
0 votes
1 answer 4 views
Problem: How to write a program that finds the duplicate words and their number of occurrences in a string? I am a beginner with no prior experience in programming so facing some difficulty in developing logic. Please help. Thanks!
asked 4 days ago Code Learner 6.5k points
0 votes
1 answer 11 views
Problem: Hello Developers! I am new to the world of programming and I started learning Java at an academy. My teacher gave us an assingment in which we have to find the index of last occurrence of a character in a string. The program should return the ... those solutions. If someone has better solution then kindly explain or else please explain what substrings are and how I can use it. Thanks
asked Nov 29, 2020 Code Learner 6.5k points
1 vote
1 answer 862 views
Problem: I am new in python programming and I have been doing a course on it as a new comer I tried to repeat some char in a string. I wrote a code : def Work(str): for i in range(len(str)): return i * 2 But it does not work . how can I do this?
asked Apr 3, 2020 LizzyM 6.1k points
0 votes
1 answer 48 views
Problem : I am very new to Java Programming and currently I am stuck with the following doubt related to Strings. How to determine if two strings are permutations of each other? Any solution on my above doubt will be appreciated.
asked Dec 25, 2019 alecxe 7.5k points
0 votes
1 answer 8 views
Problem: How would you check if a String was a number before parsing it?This is generally done with a simple user-defined function (i.e. Roll-your-own "isNumeric" function). How If it is, we can assume the entire string is numeric:?
asked Feb 15 Ali 6k points
0 votes
2 answers 131 views
Problem : How to count the number of occurrences of a character in a string in java
asked Oct 23, 2019 peterlaw 6.9k points
0 votes
1 answer 468 views
Problem : I am completely stuck on this problem Given an array of ints, return True if the array contains a 2 next to a 2 somewhere. has22([1, 2, 2]) → True has22([1, 2, 1, 2]) → False has22([2, 1, 2]) → False I know the basic idea but I am unable to implement it. ... this, eg. graph, search? def has22(mynums): for l in mynums: if ( (mynums[l] = 2) and (mynums[l+1] = 2) ) return True return False
asked Dec 10, 2019 alecxe 7.5k points