KyleHodgetts
KyleHodgetts

Reputation: 350

Why does my function only return 0 when searching through strings to find certain sub strings?

The point of this function is to search through the string to find substrings such that it starts with "foo" and ends in "bar".

E.g. foobar should return 1. foobarafoobbbarabar should return 5 because the first foo and the bar right after it count as 1, the first foo and the last bar count as another 1, the second foo and the bar that starts 3 chars after count as another 1 and finally the second foo and the last bar also count as 1, totalling 5.

Currently, i've set my function up to work like this:

public static int foobarCounter(String s)
{
   int count = 0;
   while(s.length() >0)
   {
     int startCharacter = 4; //Start character to check for bar start right after the last character of foo
     while(startCharacter + 2 < s.length()) //Prevent a string out of bounds exception
     {
       if(s.startsWith("foo"))
       {
          if(s.substring(startCharacter, startCharacter + 2) == "bar")
          {
            ++count; //add one to the count of foobars
          }
          else
          {
            ++startCharacter; //else check from the start one more character along
          }
        }
        else
        {
          s.replace(s.substring(0,1), ""); //Doesn't start with foo, remove the first character and try again
        }
    } //End of inner while loop

  } //End of while loop

return count;

} //End of method

I hope this makes sense. Thankyou

Upvotes: 0

Views: 69

Answers (2)

RonaldFindling
RonaldFindling

Reputation: 332

If it is an option for you to rewrite the function I would use something like the following. It's not a perfect solution but suitable if the data isn't too large.

public static int foobarCounter(String s) {
    int count = 0;

    String p1 = "foo";
    String p2 = "bar";
    int i = 0;
    int j = 0;

    while ((j = i = s.indexOf(p1, i)) != -1) {
        while ((j = s.indexOf(p2, j + p1.length())) != -1) { 
        //the extended stepwidth of the previous line depends on p1, p2 and is not always possible like this 
            ++count;
        }
        i = i + 1;
    }
    return count;
}

Upvotes: 0

Ascalonian
Ascalonian

Reputation: 15174

Because this:

s.substring(startCharacter, startCharacter + 2)

Only returns 2 characters, not 3. So your if-statement will never be true. Make it +3

if (s.substring(startCharacter, startCharacter + 3).equals("bar"))

You should be using equals (or equalsIgnoreCase if there is a chance the value can have capitals) instead of ==

With this, you should also change the conditions of your while-loop

Upvotes: 3

Related Questions