Glven a positive integer number and two strings S1
and S2. The task is to create another string Str3 by
merging both strings with a group of N characters
alternately, starting with S1.
Program Editor
Example 1:
Input
goby - 51
ode-S2
2-N
Output
goodbye
Explanation:
S1*goby" and S2="ode"
N = 2.
From S1, take 2 characters because N = 2; after that
take 2 characters from S2. Repeat these steps for
both strings till the end
So the output will be "goodbye".
Answers
Program in Java:
import java.util.*;
public class MyClass
{
public static void main(String args[])
{
Scanner Sc = new Scanner(System.in);
String S1, S2, S3 = "";
int N;
System.out.print("Enter first word : ");
S1 = Sc.next();
System.out.print("Enter second word : ");
S2 = Sc.next();
System.out.print("Enter a number : ");
N = Sc.nextInt();
while(S1.length()>=N && S2.length()>=N)
{
S3 = S3 + S1.substring(0,N) + S2.substring(0,N);
S1 = S1.substring(N,S1.length());
S2 = S2.substring(N,S2.length());
}
if(S1.length() != 0)
{
S3 = S3 + S1;
}
if(S2.length() != 0)
{
S3 = S3 + S2;
}
System.out.print("New word : " + S3);
}
}
Output:
Enter first word : goby
Enter second word : ode
Enter a number : 2
New word : goodbye