Social Icons

Thursday, June 24, 2010

getSandwich: Solutions for Javabat : 26


It’s been sometime since i posted my last javabat solution. Here I am with a new string question. Question is like this.

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") → ""

Source

Solution

public String getSandwich(String str) {
  int firstI = str.indexOf("bread");
  int lastI  = str.lastIndexOf("bread");
  
  if(firstI==lastI || firstI==-1)
    return "";
  else 
    return str.substring(firstI+5, lastI);  
}
 
 
Blogger Templates http://slots.to/