JAVA-8

Q.8 Write a java application which accepts two strings. Merge both the strings using alternate characters of each one. 

Solution :- 

import java.util.*;

public class MergeStrings {
    public static String mergeAlternate(String str1, String str2) {
        StringBuilder merged = new StringBuilder();
        int length1 = str1.length(), length2 = str2.length();
        int maxLength = Math.max(length1, length2);

        for (int i = 0; i < maxLength; i++) {
            if (i < length1) {
                merged.append(str1.charAt(i));
            }
            if (i < length2) {
                merged.append(str2.charAt(i));
            }
        }
        
        return merged.toString();
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter first string: ");
        String str1 = scanner.nextLine();
        System.out.print("Enter second string: ");
        String str2 = scanner.nextLine();
        scanner.close();

        String result = mergeAlternate(str1, str2);
        System.out.println("Merged String: " + result);
    }
}

TRY IT YOURSELF

TRY IT YOURSELF

Leave a Reply

Your email address will not be published. Required fields are marked *

sign up!

We’ll send you the hottest deals straight to your inbox so you’re always in on the best-kept software secrets.