KnowledgeBoat Logo

Computer Science

Write a program in Java to accept two strings. Display the new string by taking each character of the first string from left to right and of the second string from right to left. The letters should be taken alternatively from each string. Assume that the length of both the strings are same.

Sample Input:
String 1: HISTORY
String 2: SCIENCE

Sample Output:
HEICSNTEOIRCYS

Java

Java String Handling

26 Likes

Answer

import java.util.Scanner;

public class KboatString
{
    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);
        System.out.print("Enter first String: ");
        String s1 = in.nextLine();
        System.out.print("Enter second String: ");
        String s2 = in.nextLine();
        String newStr = "";
        int len = s1.length();
        
        for (int i = 0; i < len; i++) {
            char ch1 = s1.charAt(i);
            char ch2 = s2.charAt(len - 1 - i);
            newStr = newStr + ch1 + ch2;
        }
        
        System.out.println(newStr);
    }
}

Output

BlueJ output of Write a program in Java to accept two strings. Display the new string by taking each character of the first string from left to right and of the second string from right to left. The letters should be taken alternatively from each string. Assume that the length of both the strings are same. Sample Input: String 1: HISTORY String 2: SCIENCE Sample Output: HEICSNTEOIRCYS

Answered By

10 Likes


Related Questions