java

JAVA: method, how many occurrences of a string appear in another string


I'm new into learning about java programming and here I got stuck to this assignment. I can't figure out what I did wrong in the code so I can get the specific result. Any help or tips in how to solve the problem will be helpful.

This assignment will write a method to determine how many occurrences of a string appear in another string.

Specifically, you should do the following:

  1. Create a new Java Class named Part2in the StringsSecondAssignments project.

  2. Write the method named howMany that has two String parameters named stringa and stringb. This method returns an integer indicating how many times stringa appears in stringb, where each occurrence of stringa must not overlap with another occurrence of it. For example, the call howMany(“GAA”, “ATGAACGAATTGAATC”) returns 3 as GAA occurs 3 times. The call howMany(“AA”, “ATAAAA”) returns 2. Note that the AA’s found cannot overlap.

  3. Write the void method testHowMany has no parameters. Add code in here to call howMany with several examples and print the results. Think carefully about what types of examples would be good to test to make sure your method works correctly.

Here is my code:

public class Part2in {

   public String HowMany(String stringa, String stringb) {
   int lastIndex = 0;
   int count = 0;
   while (lastIndex != -1){
       lastIndex =stringb.indexOf(stringa, lastIndex);
       if(lastIndex !=-1){
           count = count + 1;
           lastIndex = stringa.length();
        }
        
       System.out.println(count);
    }
   
    return "";    
         
}
public void testHowMany() {
   
   String stringB = "ABCDASDFBCSDSDFBCBDSDBC";
   String stringA = "BC";
   String counts = HowMany(stringB, stringA);
   if (counts.isEmpty()) {
       System.out.print("ERROR" );
    }
   else {
       System.out.print("CORECT" + counts);
    }
  }
}

Solution

  • a simple while could do the work:

    @Test
    public void testIt(){
        String a = "abcdesdikdikcdkofkvcdqwppqcddddcdlpqa";
        String b = "cd";
    
        int i = 0;
        while (a.contains(b)){
            a = a.replaceFirst(b,"");
            i++;
        }
        System.out.println("found:"+i);
    
    }
    

    which prints you in my case 5