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 "";
}


3 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

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