0

I am wondering what return str.substring(1,4).equals("bad"); is doing here in the else if(len>=4). I think the if statement is a guard clause but I am not 100%. Can I have an explanation of what exactly is going on here? How is this read to output "false"?

Given a string, return true if "bad" appears starting at index 0 or 1 in the string, such as with "badxxx" or "xbadxx" but not "xxbadxx". The string may be any length, including 0. Note: use .equals() to compare 2 strings.

hasBad("badxx") → true

hasBad("xbadxx") → true

hasBad("xxbadxx") → false

public boolean hasBad(String str)
{
    int len = str.length();
    if(len == 3 && str.equals("bad"))
        return true;
    else if(len >= 4)
    {
        if(str.substring(0, 3).equals("bad"))
            return true;
        return str.substring(1, 4).equals("bad");
    }
    else
        return false;
}
M. Nelson
  • 29
  • 3
  • You want to know what `return str.substring(1, 4).equals("bad");` does? – MeetTitan Apr 21 '16 at 18:32
  • 1
    If you have no idea what this code does, why don't you ask the person who wrote it why the code is written the way it is. note: This is the same as `return str.matches(".?bad.*");` – Peter Lawrey Apr 21 '16 at 18:41

2 Answers2

2

if(str.substring(0, 3).equals("bad")) is the easy part. "Return true if 'bad' is the beginning of the String.'

return str.substring(1, 4).equals("bad") essentially means, "Return true if 'bad' occurs after the first character, and false otherwise". This is basically a shortcut of

if(str.substring(1, 4).equals("bad")) return true;
else return false; 

Because the if already evaluates a boolean (what goes inside of an if results in a boolean value), there's no reason to tell it to return "true if true, else false", you can just return the boolean value directly.

Zircon
  • 4,677
  • 15
  • 32
0

you can try it in other way too, like below one

public static boolean hasBad(String str) {
    for (int i = 0; i < str.length() - 1; i++) {

        if (str.length()>=3 && str.charAt(0) == 'b' || str.charAt(1) == 'b' ) {

            if (str.substring(i).contains("bad")) {

                return true;
            }
        }
    }
    return false;
}