Alternatively Merge two Strings in Java | Java code to alternatively merge two strings ; Function for alternatively merging two strings ; To store the final string ; For every index in the strings ; First choose the ith character of the first string if it exists ; Then choose the ith character of the second string if it exists ; Driver code
public class mergeString { public static String merge ( String s1 , String s2 ) { StringBuilder result = new StringBuilder ( ) ; for ( int i = 0 ; i < s1 . length ( ) || i < s2 . length ( ) ; i ++ ) { if ( i < s1 . length ( ) ) result . append ( s1 . charAt ( i ) ) ; if ( i < s2 . length ( ) ) result . append ( s2 . charAt ( i ) ) ; } return result . toString ( ) ; } public static void main ( String [ ] args ) { String s1 = " geeks " ; String s2 = " forgeeks " ; System . out . println ( merge ( s1 , s2 ) ) ; } }