Avatar of gudii9
gudii9Flag for United States of America asked on

getSandwich java challenge

Hi,
I am working on below challenge
http://codingbat.com/prob/p129952
I tried my code as below
public String getSandwich(String str) {
  String Str1 = new String("Welcome to Tutorialspoint.com");
  //String str2=str.replaceFirst("bread", "" );
  //System.out.println(Str.replaceFirst("Tutorials", "" ));
//String strNew= str.repalceFirst("bread", "xyzzz");
String str3=str.replaceAll(".*bread*.", "" );

  return str3;
}

 //System.out.println(Str.replaceFirst("(.*)Tutorials(.*)",
 //                        "AMROOD" ));

 //     System.out.print("Return Value :" );
 //     System.out.println(Str.replaceFirst("Tutorials", "AMROOD" ));

Open in new window

I am getting below result
Expected      Run            
getSandwich("breadjambread") → "jam"      ""      X         
getSandwich("xxbreadjambreadyy") → "jam"      "y"      X         
getSandwich("xxbreadyy") → ""      "y"      X         
getSandwich("xxbreadbreadjambreadyy") → "breadjam"      "y"      X         
getSandwich("breadAbread") → "A"      ""      X         
getSandwich("breadbread") → ""      ""      OK         
getSandwich("abcbreaz") → ""      ""      OK         
getSandwich("xyz") → ""      "xyz"      X         
getSandwich("") → ""      ""      OK         
getSandwich("breadbreaxbread") → "breax"      ""      X         
getSandwich("breaxbreadybread") → "y"      ""      X         
getSandwich("breadbreadbreadbread") → "breadbread"      ""      X         
other tests
X      

how to  improve my approach, results and design of this challenge. How do i make a graphical venn or flow chart or some other relevant diagram to design it before writing code to decide best strategy?
 Please advise
JavaJava EEJava App ServersProgramming Languages-OtherProgramming

Avatar of undefined
Last Comment
gudii9

8/22/2022 - Mon
ozo

public String getSandwich(String str) {
  return str.replaceFirst("(?:(?!bread).)*(?:bread(.*)bread)?.*","$1");
}
ASKER
gudii9

public String getSandwich(String str) {
int breadCount=0;
for(int i=0;i<str.length();i++)
{

breadCount++;
}
if(breadCount>1){
return str.replaceAll(".*bread.*","");
}
else if(breadCount==1){
return "";
}
else
return "aaa";
}

Open in new window


why above fails below
Expected      Run            
getSandwich("breadjambread") → "jam"      ""      X         
getSandwich("xxbreadjambreadyy") → "jam"      ""      X         
getSandwich("xxbreadyy") → ""      ""      OK         
getSandwich("xxbreadbreadjambreadyy") → "breadjam"      ""      X         
getSandwich("breadAbread") → "A"      ""      X         
getSandwich("breadbread") → ""      ""      OK         
getSandwich("abcbreaz") → ""      "abcbreaz"      X         
getSandwich("xyz") → ""      "xyz"      X         
getSandwich("") → ""      "aaa"      X         
getSandwich("breadbreaxbread") → "breax"      ""      X         
getSandwich("breaxbreadybread") → "y"      ""      X         
getSandwich("breadbreadbreadbread") → "breadbread"      ""      X         
other tests
ASKER
gudii9

public String getSandwich(String str) {
int breadCount=0;
for(int i=0;i<str.length();i++)
{

breadCount++;
}
if(breadCount>1){
return str.replaceAll("bread","");
}
else if(breadCount==1){
return "";
}
else
return "aaa";
}

Open in new window


above fails some too

Expected      Run            
getSandwich("breadjambread") → "jam"      "jam"      OK         
getSandwich("xxbreadjambreadyy") → "jam"      "xxjamyy"      X         
getSandwich("xxbreadyy") → ""      "xxyy"      X         
getSandwich("xxbreadbreadjambreadyy") → "breadjam"      "xxjamyy"      X         
getSandwich("breadAbread") → "A"      "A"      OK         
getSandwich("breadbread") → ""      ""      OK         
getSandwich("abcbreaz") → ""      "abcbreaz"      X         
getSandwich("xyz") → ""      "xyz"      X         
getSandwich("") → ""      "aaa"      X         
getSandwich("breadbreaxbread") → "breax"      "breax"      OK         
getSandwich("breaxbreadybread") → "y"      "breaxy"      X         
getSandwich("breadbreadbreadbread") → "breadbread"      ""      X         
other tests
X
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
SOLUTION
ozo

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
gudii9

  return str.replaceFirst("(.*?bread(.*)bread)?.*","$2");

Open in new window


what is the logic and meaning of above solution
replacing all characters before(.*?bread) and after bread(bread)?.*",) with $2?
ozo

In a replacement string, $2 represents the string matched by the 2nd pair of capturing parentheses.
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ozo

return str.indexOf("bread") == str.lastIndexOf("bread") ? "" :
       str.substring(str.indexOf("bread") + 5, str.lastIndexOf("bread"));

Open in new window

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ozo

public String getSandwich(String str) {
    int first=Math.min(str.indexOf("bread")+5,str.length());
    int last=Math.max(str.lastIndexOf("bread"),first);
    return str.substring(first,last);
}

Open in new window

ASKER
gudii9

str.substring(str.indexOf("bread") + 5

why we are adding to 5

in below solution

public class HelloWorld{
     public static void main(String []args){
        System.out.println("Hello World"+ getSandwich("breadjambread"));
     }
     
     public  static String getSandwich(String str) {

return str.indexOf("bread") == str.lastIndexOf("bread") ? "" : str.substring(str.indexOf("bread") + 5, str.lastIndexOf("bread"));
}

}
ozo

why we are adding 5
To get from the index of the beginning of "bread" to the index of the end of "bread"
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
ASKER
gudii9

public class HelloWorld{
     public static void main(String []args){
        System.out.println("Hello World"+ getSandwich("breadAbread"));
     }
     
     public  static String getSandwich(String str) {
    	 System.out.println("  is-->"+ str.indexOf("bread"));
    	 System.out.println("  last is-->"+ str.lastIndexOf("bread"));

return str.indexOf("bread") == str.lastIndexOf("bread") ? "" 
		: str.substring(str.indexOf("bread") + 5, str.lastIndexOf("bread"));
}

}

Open in new window


above gave below right output.

  is-->0
  last is-->6
Hello WorldA


so we are checking indexOf ==lastIndex which means only one bread then return ""
otherwise we are basically asking to print middle sandwitched part using

str.substring(str.indexOf("bread") + 5, str.lastIndexOf("bread"))
ASKER
gudii9

public String getSandwich(String str) {
  return str.replaceFirst("(?:(?!bread).)*(?:bread(.*)bread)?.*","$1");
}

how to test above in regex101 site?

i should only take as bolded above by ignoring all the java statements?
ozo

Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
gudii9

why we need substitution variable as

$1

if i remove that how to re run
to see new output

please advise
ozo

ASKER
gudii9

as attached i am not able to see output now at bottom most section.


How to get output.

what is the button i have to click to see output?

https://regex101.com/r/gT1yH8/2
jam.png
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
ASKER
gudii9

what is meaning of $1 in substitution?
ozo

https://regex101.com/r/gT1yH8/3
Substitution
Contents in capture group 1  $1
This will return a string with the contents from the first capture group. The number, in this case 1, can be any number as long as it corresponds to a valid capture group.
ASKER
gudii9

what is difference between capturing group and substitution. are both same?
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ozo

A capturing group is a pair of (parentheses) in the regular expression -- except when the pattern in the parentheses starts with ?

A substitution is the second argument in a replaceFirst(pattern,substitution) call in Java,
or what you enter in the Substitution input box in regex101.com

In a Java (or regex101) substitution, "$1" gets replaced by what was matched by the 1st capturing group.
ASKER
gudii9

if i remove that how to re run
to see new output

so there is no submit button ..looks like site itself is running and giving output automatically