Skip to content

Instantly share code, notes, and snippets.

@harshityadav95
Created December 9, 2017 11:10
Show Gist options
  • Save harshityadav95/a11d91077a09c5a419d3a94defaec1c2 to your computer and use it in GitHub Desktop.
Save harshityadav95/a11d91077a09c5a419d3a94defaec1c2 to your computer and use it in GitHub Desktop.
Sandwhich String
/* 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") → ""
link: http://www.javaproblems.com/2013/11/java-string-2-getsandwich-codingbat.html
*/
static String getSandwich(String inputString) {
int firstPos = inputString.indexOf("bread");
int lastPos = inputString.lastIndexOf("bread");
if ( firstPos != -1 && lastPos != -1 && firstPos != lastPos )
return inputString.substring(firstPos+5, lastPos);
else
return "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment