Java > String-1 > seeColor (CodingBat Solution)

Problem:

Given a string, if the string begins with "red" or "blue" return that color string, otherwise return the empty string.

seeColor("redxx") → "red"
seeColor("xxred") → ""
seeColor("blueTimes") → "blue"


Solution:

public String seeColor(String str) {
  if (str.startsWith("red"))
    return "red";
  if (str.startsWith("blue"))
    return "blue";
  else
    return "";
}


9 comments :

  1. public String seeColor(String str) {

    if(str.length()>2 && "red".equals(str.substring(0,3)))
    return "red";

    else if(str.length()>3 && "blue".equals(str.substring(0,4)))
    return "blue";

    else return "";
    }

    ReplyDelete
  2. public String seeColor(String str) {

    if(str.length() >= 3 && str.substring(0,3).equals("red")) {
    return "red";
    } else if (str.length() >= 4 && str.substring(0,4).equals("blue")) {
    return "blue";
    }

    return "";

    }

    ReplyDelete
  3. public String seeColor(String str) {

    int redIndex= str.indexOf("red");
    int blueIndex = str.indexOf("blue");

    if (redIndex == 0)
    return "red";
    else if (blueIndex == 0)
    return "blue";
    else
    return "";
    }

    ReplyDelete
  4. public String seeColor(String str) {
    if(str.startsWith("red")){
    return str.substring(0,3);
    } if(str.startsWith("blue")){
    return str.substring(0,4);
    }
    else return "";
    }

    ReplyDelete
  5. public String seeColor(String str) {
    if(str.indexOf("red") == 0) return "red";
    if(str.indexOf("blue") == 0) return "blue";

    return "";
    }

    ReplyDelete
  6. return (str.length()>=2 && (str.substring(0,2).equals(str.substring(str.length()-2))));

    ReplyDelete
  7. if (str.length()<=3 && !str.equals("red"))
    return "";
    if (str.substring(0,3).equals("red"))
    return "red";
    if (str.substring(0,4).equals("blue"))
    return "blue";
    return "";

    ReplyDelete

  8. return str.startsWith("blue") ? "blue" : str.startsWith("red") ? "red" : "";

    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