Answer:
import java.util.*;
class Main
{
private String[] totalSandwiches(String string1,String string2)
{
int totalElements = string1.length()-1;
String ans[] = new String[totalElements];
for(int i=0;i<totalElements;i++)
{
String temp = "";
for(int j=0;j<=i;j++)
{
temp+=string1.charAt(j);
}
temp+=string2;
for(int j=i+1;j<string1.length();j++)
{
temp+=string1.charAt(j);
}
ans[i] = temp;
}
return ans;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
Main obj = new Main();
String string1,string2;
System.out.print("Enter the 1st String: ");
string1 = sc.nextLine();
while(string1.length()<2)
{
System.out.print("The size of string 1 should be atleast 2 to make a sandwich. Enter the string again: ");
string1 = sc.nextLine();
}
System.out.print("Enter the 2nd String: ");
string2 = sc.nextLine();
while(string2.length()==0)
{
System.out.print("The size of string 2 should be atleast 1 to make a sandwich. Enter the string again: ");
string2 = sc.nextLine();
}
System.out.println("Following are the sandwiches: ");
String ans[] = obj.totalSandwiches(string1,string2);
for(int i=0;i<ans.length;i++)
{
System.out.println(ans[i]);
}
}
}
Explanation:
- Run a while loop upto the total no. of elements and calculate number of elements from the string1 that should come before string2
.
-
Append the remaining characters of string1 are to temp.
- The ans array stores the temp at ith index.
- string1 characters are stored by the variable j.
- Sandwich is not possible if string1 has less than 2 elements and possible if string2 has no elements.
- Finally display the sandwich strings.