Thursday, February 29, 2024
HomeSoftware EngineeringTaking part in with the letter ‘E’ in Java

Taking part in with the letter ‘E’ in Java


The problem

Given String str, return:

  • If given String doesn’t comprise any “e”, return: “There is no such thing as a “e”.”
  • If given String is empty, return empty String.
  • If given String is `null`

The answer in Java code

Choice 1:

public class WithoutLetterE {
  public static String findE(String str){
    if (str==null) return null;
    if (str.equals("")) return "";
    int len = str.size() - str.toLowerCase().replaceAll("e", "").size();
    if (len > 0) return String.valueOf(len);
    if (!str.accommodates("e")) return "There is no such thing as a "e".";
    return null;
  }
}

Choice 2:

public class WithoutLetterE {
  public static String findE(String str) str == "") return str;
    int i = str.replaceAll("[^eE]", "").size();
    return i == 0 ? "There is no such thing as a "e"." : "" + i + "";
  
}

Choice 3:

public class WithoutLetterE {
    public static String findE(String str) {
        if (str == null) return null;
        int size = str.replaceAll("(?i)[^e]", "").size();
        return str.isEmpty() ? "" : size > 0 ? String.valueOf(size) : "There is no such thing as a "e".";
    }
}

Check instances to validate our answer

import static org.junit.Assert.assertEquals;
import org.junit.Check;
public class WithoutLetterETest {
  @Check
  public void findE() {
    assertEquals("Ought to return "There is no such thing as a "e"."", "There is no such thing as a "e".", WithoutLetterE.findE("precise"));
    assertEquals("Ought to return "1"", "1", WithoutLetterE.findE("e"));
    assertEquals("Ought to return "1"", "1", WithoutLetterE.findE("English"));
    assertEquals("Ought to return "4"", "4", WithoutLetterE.findE("English train"));
    assertEquals("Ought to return """, "", WithoutLetterE.findE(""));
    assertEquals("Ought to return null", null, WithoutLetterE.findE(null));
  }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments