HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

java if `String` begins with "red" or "blue"

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
withredbluejavabeginsstring

Problem

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

public String seeColor(String str) {
  if(str.length() <= 3){
    if(str.equals("red")){
      return "red";
    }
    return "";
  }
  else if(str.substring(0, 3).equals("red")){
    return "red";
  }
  else if(str.substring(0, 4).equals("blue")){
    return "blue";
  }
  return "";
}


I really don't like the fact that I'm using same code for "red" twice but I can't get to think out another way. If str is equal to 3, I have to make the check for "red", right?
Example input: "redxx" - output "red",
"xxred" - output "",
"blueAvenue" - output "blue"

Solution

Why aren't you using String.startsWith(prefix)? This should be a one-liner.

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

Code Snippets

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

Context

StackExchange Code Review Q#113661, answer score: 14

Revisions (0)

No revisions yet.