2. Write a Java program that generates a new string by concatenating the reversed substrings of even indexes and odd indexes separately from a given string. For this code you may use the above method to reverse the string. [10 points] Example #1 Input: abscacd Output: dasaccb Explanation: Substring are: asad, bcc Reversed substrings are: dasa, ccb Output: dasaccb

Respuesta :

Answer:

  1. public class Main {
  2.    public static void main(String[] args) {
  3.        String testString = "abscacd";
  4.        String evenStr = "";
  5.        String oddStr = "";
  6.        for(int i=testString.length() - 1; i >= 0; i--){
  7.            if(i % 2 == 0){
  8.                evenStr += testString.charAt(i);
  9.            }
  10.            else{
  11.                oddStr += testString.charAt(i);
  12.            }
  13.        }
  14.        System.out.println(evenStr + oddStr);
  15.    }
  16. }

Explanation:

Firstly, let declare a variable testString to hold an input string "abscacd" (Line 1).

Next create another two String variable, evenStr and oddStr and initialize them with empty string (Line 5-6). These two variables will be used to hold the string at even index and odd index, respectively.

Next, we create a for loop that traverse the characters of the input string from the back by setting initial position index i to  testString.length() - 1  (Line 8). Within the for-loop, create if and else block to check if the current index, i is divisible by 2, (i % 2 == 0), use the current i to get the character of the testString and join it with evenStr. Otherwise, join it with oddStr (Line 10 -14).

At last, we print the concatenated evenStr and oddStr (Line 18).  

ACCESS MORE