0

Suppose:

String s1="13579";
String s2="2468";

then output would be 123456789

Here my code :

public class JoinString {

    public static void main(String[] args) {

        String s1 = "13579"; 
        String s2 = "2468";
        for (int i = 0; i < s1.length(); i++) {
            for (int j = i; j < s2.length(); j++) {

                System.out.print(s1.charAt(i) + "" + s2.charAt(j));
                break;
            }
        }
    }
}
Prashant Gaurav
  • 49
  • 3
  • 10

6 Answers6

3
StringBuilder buf = new StringBuilder();
for (int i = 0; i < Math.max(s1.length(), s2.length()); i++) {
    if (i < s1.length()) {
        buf.append(s1.charAt(i));
    }
    if (i < s2.length()) {
        buf.append(s2.charAt(i));
    }
}
final String result = buf.toString();

You only need one loop. Also, you can use a StringBuilder class to build your string character by character.

Roman Puchkovskiy
  • 11,415
  • 5
  • 36
  • 72
3

How about this little trick:

String s1 = "13579"; 
String s2 = "2468";

String s3 = (s1 + s2).codePoints() // stream of code points
    .sorted()
    // collect into StringBuilder
    .collect(StringBuilder::new, StringBuilder::appendCodePoint,  StringBuilder::append) 
    .toString();

System.out.println(s3); // 123456789 
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93
  • But that only works if the inputs are strictly sorted. Can we really assume that's always the case? – azurefrog May 24 '17 at 18:56
  • @azurefrog I was just wondering about that. tbh I thought that was the whole point, to get sorted output. – Jorn Vernee May 24 '17 at 18:57
  • Hmm, good point, looking back at it, the OP's question could be read as "every other character" or "sorted output", it's sort of ambiguous. – azurefrog May 24 '17 at 18:58
2

A simple way to achieve that is by doing something like this:

String s1 = "13579"; 
String s2 = "2468";
char[]result = (s1+s2).toCharArray();
Arrays.sort(result);
System.out.println(result);

Output:

123456789
Yahya
  • 13,349
  • 6
  • 30
  • 42
1

You just need to combine the logic of the two loops like this (and use StringBuilder if you want to build a string this way).

    String s1 = "13579"; 
    String s2 = "2468";
    int length = Math.max(s1.length(), s2.length());
    for (int i = 0; i < length; i++) {
        if(i < s1.length())
          System.out.print(s1.charAt(i));

        if(i < s2.length())
          System.out.print(s2.charAt(i));
    }
Tezra
  • 8,463
  • 3
  • 31
  • 68
0

Similar to @Roman Puchovskiy, here is a way to do it without the StringBuilder.

    String s1 = "abcde";
    String s2 = "defgh";
    String combined = "";
    int length = s1.length() > s2.length() ? s1.length() : s2.length(); //Finds the longest length of the two, to ensure no chars go missing
    for(int i = 0 ; i < length ; i++) {
        if(i < s1.length()) { // Make sure there is a char in s1 where we're looking.
            combined += s1.charAt(i);
        }
        if(i < s2.length()) { // Same with s2.
            combined += s2.charAt(i);
        }
    }

Where combined becomes the combined string. ("adbecfdgeh").

Hope this helps!

Chris Gilardi
  • 1,509
  • 14
  • 26
  • 1
    Please note that this will produce a lot of garbage: a string object per `+=`, so an object per resulting string character. A GC may not be happy. – Roman Puchkovskiy May 24 '17 at 18:59
  • @RomanPuchkovskiy thanks for the insight, I wasn't aware that this was the case. However, I did just read in [this answer](https://stackoverflow.com/a/4323132/4914803) that it may not matter, because Java's compiler is smart enough to turn it to a `StringBuilder`. Either way, thanks! – Chris Gilardi May 24 '17 at 19:04
  • 2
    @ChrisGilardi the compiler does do that, but then `toString` is called each time the loop runs, while with a `StringBuilder`, that happens only once. May not be noticiable here, but this does take more memory than a `StringBuilder` solution. For single statement, it doesn't matter. But within loops, it makes a considerable difference. – dumbPotato21 May 24 '17 at 19:06
  • @ChandlerBing Well alrighty, I stand corrected! Thanks for letting me know, I'll remember that for my own projects! – Chris Gilardi May 24 '17 at 19:07
  • @ChrisGilardi No worries :) I also recommend reading this https://stackoverflow.com/a/47758/5055190 – dumbPotato21 May 24 '17 at 19:09
0

Similar way as merge method in merge sort.

Also it's better if you convert string to char array so that random access to element is in constant time. Because charAt has O(n) time complexity.

public class JoinString {

public static void main( String[] args ) {

    String s1 = "13579";
    String s2 = "2468";
    final char[] str1 = s1.toCharArray();
    final char[] str2 = s2.toCharArray();
    int i;
    for ( i = 0; i < str1.length && i < str2.length; i++ ) {
        System.out.print( str1[i] + "" + str2[i] );
    }

    while ( i < str1.length ) {
        System.out.print( str1[i] + "" );
        i++;
    }

    while ( i < str2.length ) {
        System.out.print( str2[i] + "" );
        i++;
    }
}

}

swapnil
  • 230
  • 3
  • 6
  • For `String`, `StringBuffer`, and `StringBuilder`, `charAt()` is a constant-time operation. https://stackoverflow.com/questions/6461402/java-charat-and-deletecharat-performance – Roman Puchkovskiy May 25 '17 at 05:29