Define a class to accept two strings of the same length and form a new word in such a way that the first character of the first word is followed by the first character of the second word and so on. Example: Input string 1 - BALL Input string 2 - WORD OUTPUT : BWAOLRLD
Topic: Merging two strings character by character
Answer
import java.util.Scanner;
class MergeStrings { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.print("Enter the first string : "); String s1 = sc.next(); System.out.print("Enter the second string : "); String s2 = sc.next();
if(s1.length() != s2.length()) { System.out.println("The strings are not of the same length"); } else { String res = ""; for(int i = 0; i < s1.length(); i++) res = res + s1.charAt(i) + s2.charAt(i);
System.out.println("Merged word : " + res); } } }
The pattern is called interleaving, and one loop does the whole job: at each index take a character from each string and append both.
Because both strings have the same length, a single index i serves for both — s1.charAt(i) and s2.charAt(i). That is why the question specifies equal lengths, and why a good answer checks the condition before starting rather than crashing with a StringIndexOutOfBoundsException.
One Java subtlety worth knowing: in res + s1.charAt(i) + s2.charAt(i) the additions run left to right, and because res is a String, each char is joined as text rather than added as a number. Had you written s1.charAt(i) + s2.charAt(i) on its own, Java would have ADDED their ASCII values and produced a number — a real trap.
Trace the sample: B+W, A+O, L+R, L+D gives BWAOLRLD, exactly as the question shows.
s1 String - the first string entered by the user s2 String - the second string entered by the user res String - the merged word built up character by character i int - loop variable, the common index into both strings sc Scanner - object used to read input