-1

I have a task where I'm asked to create a method that merges multiple Strings so that the first character in the first string is followed by the first character in the 2nd String followed by the first character in the 3rd string and so on.

public static String merge(String... s)

if I would merge("AH", "HI", "U") the result would be AHUHI. I'm just not quite sure how to deal with this problem when the amount of Strings are unknown, someone has any idea how this could be executed?¨

This is what I tried:

public static String merge(String... s)
    {
        StringBuilder b = new StringBuilder();

         for(int i = 0; i < s.length ; i++)
         {
             for(int y = 0; y < s.length ; y++)
             {
             b.append(s[y].charAt(i));
             }
         }
         return b.toString();
    }

and this is the exception I got:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0

Mike G
  • 4,232
  • 9
  • 40
  • 66

5 Answers5

2
  • Find maxLength (the length of the longest String in your arguments) and change the outerloop to iterate maxLength times

  • Before you access a char of a String via charAt() check if the String is long enough, so you wont get the StringIndexOutOfBoundsException

Since you are already dealing with multiple input Strings, the code should work fine after these changes.

public static String merge(String... strings)
{
    int maxLength = 0;
    StringBuilder sb = new StringBuilder();

    // find the longest
    for (String s : strings)
        if (s.length() > maxLength)
            maxLength = s.length();

    // build the output string
    for (int i = 0; i < maxLength; i++)
        for (String s : strings)
            if (s.length() > i)
                sb.append(s.charAt(i));

    return sb.toString();
}
kai
  • 6,702
  • 22
  • 38
1

You're on the right lines, but you need to check that each string you're referencing is big enough not to throw the StringIndexOutOfBoundsException. So first, try getting the max string length:

public static String merge(String... s)
{

    int maxLen = 0;
    for (String str : s) // this loops through each string in the array s
    {
        maxLen = Math.max(maxLen, str.length());
    }

    // maxLen is now the length of the longest string;

    StringBuilder b = new StringBuilder();

    for (int i = 0; i < maxLen; ++i) // for each character position up to the max...
    {
         for (String str : s) // loop through each string:
         {
             if (str.length() > i) // check whether current string has any characters left
             {
                 b.append(str.charAt(i));
             }
         }
     }
     return b.toString();
}
daiscog
  • 11,441
  • 6
  • 50
  • 62
1

Thats how I would do it: Basically, you loop though every String and always take the 1st, 2nd, 3rd, ... character of the String and append it to the StringBuilder.

private static String merge(String... strings) {
    StringBuilder sb = new StringBuilder();
    int adv;
    boolean edited;

    adv = 0;
    edited = true;
    while (edited) {
        edited = false;
        for (String s : strings) {
            if (adv < s.length()) {
                sb.append(s.charAt(adv));
                edited = true;
            }
        }
        adv++;
    }
    return sb.toString();
}
redxef
  • 492
  • 4
  • 12
0

This is how I would do it:

public static String merge(String... s)
{
    // Here we create a StringBuilder, this will store our result string
    StringBuilder b = new StringBuilder();

    // This boolean will control when we stop appending
    boolean appended = true;

    // The outer loop will loop over the indices of the available characters
    // until we have no more characters to append
    for (int i = 0; appended; ++i) {
        // We have to default this to false to start our loop so that we don't
        // exit early
        appended = false;
        // Loop over the individual strings that we were passed
        for (String item : s) {
            // If the string we are looking at has a character at the current
            // position, we append it to our StringBuilder, otherwise we skip
            // it
            if (i < item.length()) {
                b.append(item.charAt(i));
                // Because we appeneded a character, we might have additional
                // characters, so set this so that our loop continues
                appended = true;
            }
        }
    }
    // Now we call the toString() method of StringBuilder to get a String
    // result, which we return to our caller.
    return b.toString();
}
Sean Bright
  • 118,630
  • 17
  • 138
  • 146
  • `for (int i = 0; append; ++i)` would be more readable IMHO. (That's unrelated to your previous comment. I wouldn't down-vote because of a stylistic issue.) – 5gon12eder Sep 21 '15 at 14:40
  • i did not downvote you, i wish i could upvote but i think i need points. This is not exacly how the task i was asked should b done, but you surely gave me a very good clue on how to deal with it. Im very thankful – Jesus Petrucci Sep 21 '15 at 14:43
  • @5gon12eder - Agreed. I've updated with your suggestion. – Sean Bright Sep 21 '15 at 14:45
  • Nice solution. Add some explanatory comments and you'll get an upvote from me :-) – daiscog Sep 21 '15 at 14:50
  • Hehe, witty, but good comments explain _how_, not what it does – daiscog Sep 21 '15 at 14:53
  • 1
    I hope that the comments I have added are adequate. If not, please let me know and I will add some more. – Sean Bright Sep 21 '15 at 15:11
-2

Split each String into a array. Similar to this: Split string into array of character strings

Then go through the array and take out index 0 and assign it to a new string, and do that for index 1, and so on.

Community
  • 1
  • 1
JP Hochbaum
  • 637
  • 4
  • 15
  • 28