90.4k views
3 votes
Given the strings s1 and s2 that are of the same length, create a new string consisting of the last character of s1 followed by the last character of s2, followed by the second to last character of s1, followed by the second to last character of s2, and so on (in other words the new string should consist of alternating characters of the reverse of s1 and s2). For example, if s1 contained hello" and s2 contained "world", then the new string should contain "odlllreohw". Assign the new string to the variable s3.

1 Answer

4 votes

Answer:

See the code snippet in the explanation section

Step-by-step explanation:

import java.util.Scanner;

public class Question {

public static void main(String args[]) {

Scanner scan = new Scanner(System.in);

System.out.println("Enter first string: ");

String s1 = scan.nextLine();

System.out.println("Enter second string: ");

String s2 = scan.nextLine();

concatenateString(s1, s2);

}

public static void concatenateString(String firstString, String secondString){

int stringLength = firstString.length() - 1;

String s3 = "";

if (firstString.length() != secondString.length()){

System.out.println("String do not have equal length");

} else {

for(int i = stringLength; i >= 0; i--){

s3 += String.valueOf(firstString.charAt(i)).concat(String.valueOf(secondString.charAt(i)));

}

System.out.println(s3);

}

}

}

User EJK
by
4.5k points