Ask Question

Write the WordSandwich method allSandwiches. This method creates and returns a new array of String objects as follows. Each element of the array will be a sandwich of str1 and str2: that is the characters of str2 are inserted into str1. The first String in the array consists of 1 letter of str1 followed by str2, followed by the rest of the letters of str1. For each subsequent String in the array the position in str1 where str2 starts is shifted by 1 until the final string in the array which consists of all but 1 letter of str1 followed by str2, followed by the final remaining letter of str1. For example, the call allSandwiches ("bread", "ham") will return the following array.

+3
Answers (1)
  1. 2 November, 14:56
    0
    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
    {

    String temp = "";

    for (int j=0; j<=i; j++)

    {

    temp+=string1. charAt (j);

    }

    temp+=string2;

    for (int j=i+1; 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
    {

    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.
Know the Answer?
Not Sure About the Answer?
Find an answer to your question 👍 “Write the WordSandwich method allSandwiches. This method creates and returns a new array of String objects as follows. Each element of the ...” in 📗 Computers & Technology if the answers seem to be not correct or there’s no answer. Try a smart search to find answers to similar questions.
Search for Other Answers