简体   繁体   中英

Merge 2 strings by printing the characters from each String one after the other

This is an interview which was asked recently. Suppose there are 2 strings.

String a="test"; String b="lambda";

Reverse the String.

//tset //adbmal

Expected output should be: tasdebtmal

Here we are trying to print characters from each string. "t" from 1st String is printed, followed by "a" from other string, and so on. So, "tasdebtm" is printed from each string and the remaining characters "al" is appended at the end.

int endA = a.length() - 1;
int endB = b.length() - 1;
StringBuilder str = new StringBuilder();

//add values to str till both the strings are not covered
while(endA>-1 && endB>-1){
    str.append(a.charAt(endA--));
    str.append(b.charAt(endB--));
}

add all chars of a if any is remaining
while(endA>-1){
   str.append(a.charAt(endA--));
}

add all chars of b if any is remaining
while(endB>-1){
   str.append(b.charAt(endB--));
}
System.out.println(str);

Definitely, there are other ways to do this too.

public class CharsinString2 {

public static void main(String[] args) {
    
    String a="abra";  //arba
    String b="kadabra";//arbadak  // aarrbbaadak
    
    int endA=a.length()-1;
    int endB=b.length()-1;
    
    StringBuilder str=new StringBuilder();
    
    while(endA>-1 && endB>-1) {
        
        str.append(a.charAt(endA--));
        str.append(b.charAt(endB--));
        
    }
    
    
    while(endA>-1) {
        str.append(a.charAt(endA--));
    }
    
    while(endB>-1) {
        str.append(b.charAt(endB--));
    }
    
    System.out.println(str);
    
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM