Java > String-1 > hasBad (CodingBat Solution)

Problem:

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


Solution:

public boolean hasBad(String str) {
  if(str.length() < 3)
    return false;
  else if ((str.substring(0,3)).equals("bad"))
    return true;
  else if (str.length() > 3){
    if ((str.substring(1,4)).equals("bad"))
      return true;
  }
    return false;
}


6 comments :

  1. public boolean hasBad(String str) {
    String bad = "bad";

    if(str.length()<=3 && !str.contains(bad)){
    return false;
    }
    if(str.startsWith(bad) || str.substring(1, 4).startsWith(bad)){
    return true;
    }
    return false;
    }

    ReplyDelete
  2. String badStr = "bad";

    if (str.length() < 3) {
    return false;
    }

    if (str.substring(0, 3).equals(badStr)) {
    return true;
    }

    if ( str.length() > 3 && str.substring(1, 4).equals(badStr)) {
    return true;
    } else {
    return false;
    }
    }

    ReplyDelete
  3. public boolean hasBad(String str) {
    return str.length()>=3?str.substring(0,3).equals("bad")
    ||
    str.length()>3&&str.substring(1,4).equals("bad"):false;
    }

    ReplyDelete
  4. public boolean hasBad(String str) {
    if(str.length()<3) {
    return false;
    }
    if (str.substring(0).startsWith("bad") || str.substring(1).startsWith("bad")){
    return true;
    }
    return false;
    }

    ReplyDelete
  5. public final boolean hasBad(String str) {
    return !str.isEmpty() && (str.startsWith("bad")
    || str.substring(1).startsWith("bad"));
    }

    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