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;
            }
        }
    }
}
12
  • 5
    What's your reasoning for that break? Commented May 24, 2017 at 18:46
  • 5
    You don't really need two nested loops there. Just one loop that keeps track of an index into both strings is sufficient. Once you've run out of the shorter one, you can just append a substring of the longer one based on how far into it you've gotten. Commented May 24, 2017 at 18:48
  • if i didnt use break statement, then op will be 12141618343638565878 . Commented May 24, 2017 at 18:49
  • 3
    Does output need to be sorted? Or interleaved? It's unclear. Commented May 24, 2017 at 18:58
  • 2
    @PrashantGaurav If s1="97531" and s2="2468", what output would you expect? 123456789 or 927456381? Commented May 24, 2017 at 19:02

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

Comments

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 

3 Comments

But that only works if the inputs are strictly sorted. Can we really assume that's always the case?
@azurefrog I was just wondering about that. tbh I thought that was the whole point, to get sorted output.
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.
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

3 Comments

But that only works if the inputs are strictly sorted. Can we really assume that's always the case?
@azurefrog What do you mean by strictly sorted?, I used the example the OP mentioned.
True, see my reply on @Jorn Vernee's answer. The OP's question is ambiguous.
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));
    }

2 Comments

This might be a little redundant with the double checking of s1.length() and s2.length().
@ChrisGilardi true... Broke out that bit so that the while loop does minimal work on while part.
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!

5 Comments

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.
@RomanPuchkovskiy thanks for the insight, I wasn't aware that this was the case. However, I did just read in this answer that it may not matter, because Java's compiler is smart enough to turn it to a StringBuilder. Either way, thanks!
@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.
@ChandlerBing Well alrighty, I stand corrected! Thanks for letting me know, I'll remember that for my own projects!
@ChrisGilardi No worries :) I also recommend reading this stackoverflow.com/a/47758/5055190
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++;
    }
}

}

1 Comment

For String, StringBuffer, and StringBuilder, charAt() is a constant-time operation. stackoverflow.com/questions/6461402/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.