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" : "";
Here is a full example using a list to hold your colors, and Str.startsWith:
import java.io.*;
import java.util.*;
class Main {
static final List<String> colors = Arrays.asList("red", "blue");
static public String seeColor(String str) {
for (String color : colors ) {
if (str.startsWith(color)) {
return color;
}
}
return "";
}
public static void main(String[] args) {
List<String> testColors = Arrays.asList("redxx", "xxred", "blueAvenue");
for (String testColor: testColors) {
System.out.println(testColor + " -> " + seeColor(testColor));
}
}
}
Note than when checking for multiple colors, you can only return if the for
loop matches, and keep the empty return after the loop. In addition notice the simple but subtle naming differentiation between color
and colors
which makes it easy to distinguish between the list and a single element.
As @200_success said, String.startsWith
is great and its use simplifies the code down to:
return str.startsWith("red") ? "red" : str.startsWith("blue") ? "blue" : "";
I used a nested ternary, but it still is very easy to undertand, and I do not fell like bloating this easy function with if
and elif
statements.