EIP EIP - 3 months ago 29
Java Question

Return the string that is between the first and last appearance of "bread" in the given string

This question is from coding bat and might have been asked before. Please review the code.

A sandwich is two pieces of bread with something in between. Return the string that is between the first and last appearance of "bread" in the given string, or return the empty string "" if there are not two pieces of bread.

getSandwich("breadjambread") → "jam"
getSandwich("xxbreadjambreadyy") → "jam"
getSandwich("xxbreadyy") → ""


My code is

public static String getSandwich(String str) {
int ind = str.indexOf("bread");
int laind = str.lastIndexOf("bread");
if(!(laind == -1 ))return (str.substring(ind+5,laind)) ;
return "";
}


And i am getting

Exception:java.lang.StringIndexOutOfBoundsException: String index out of range: -5 (line number:4)


for this input
getSandwich("xxbreadyy")

Answer

See the following code

public static String getSandwich(String str) {
    int ind = str.indexOf("bread");
    int laind = str.lastIndexOf("bread");
    if((laind != -1 ) && (ind!=laind))
        return (str.substring(ind+5,laind)) ;
    return "";
}

I added (ind!=laind) to the condition which checks if the first and the last "bread" are NOT same.

See live demo here.