The challenge
Given String str
, return:
- If given String doesn’t contain any “e”, return: “There is no “e”.”
- If given String is empty, return empty String.
- If given String is `null`
The solution in Java code
Option 1:
public class WithoutLetterE {
public static String findE(String str){
if (str==null) return null;
if (str.equals("")) return "";
int len = str.length() - str.toLowerCase().replaceAll("e", "").length();
if (len > 0) return String.valueOf(len);
if (!str.contains("e")) return "There is no \"e\".";
return null;
}
}
Option 2:
public class WithoutLetterE {
public static String findE(String str){
if(str == null || str == "") return str;
int i = str.replaceAll("[^eE]", "").length();
return i == 0 ? "There is no \"e\"." : "" + i + "";
}
}
Option 3:
public class WithoutLetterE {
public static String findE(String str) {
if (str == null) return null;
int length = str.replaceAll("(?i)[^e]", "").length();
return str.isEmpty() ? "" : length > 0 ? String.valueOf(length) : "There is no \"e\".";
}
}
Test cases to validate our solution
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class WithoutLetterETest {
@Test
public void findE() {
assertEquals("Should return \"There is no \"e\".\"", "There is no \"e\".", WithoutLetterE.findE("actual"));
assertEquals("Should return \"1\"", "1", WithoutLetterE.findE("e"));
assertEquals("Should return \"1\"", "1", WithoutLetterE.findE("English"));
assertEquals("Should return \"4\"", "4", WithoutLetterE.findE("English exercise"));
assertEquals("Should return \"\"", "", WithoutLetterE.findE(""));
assertEquals("Should return null", null, WithoutLetterE.findE(null));
}
}