Search code examples
c#stringmergenumeric

Merge 2 Numeric strings Alternatively every Nth place


I have 2 Numeric strings with commas:

8,1,6,3,16,9,14,11,24,17,22,19 and 2,7,4,5,10,15,12,13,18,23,20,21

and I need to merge them Alternatively every Nth place (for Example every 4th place to get)

8,1,2,7,6,3,4,5,16,9,10,15,14,11,12,13,24,17,18,23,22,19,20,21

I've already examined all recommended solutions but nothing worked for me.

Here's my current progress:

string result = "";

// For every index in the strings
for (int i = 0; i < JoinedWithComma1.Length || i < JoinedWithComma2.Length; i=i+2)
{
    // First choose the ith character of the
    // first string if it exists
    if (i < JoinedWithComma1.Length)
        result += JoinedWithComma1[i];

    // Then choose the ith character of the
    // second string if it exists
    if (i < JoinedWithComma2.Length)
        result += JoinedWithComma2[i];
}

Appreciate any assistance.


Solution

  • You can't rely on the length of the strings or select the "ith character" because not all "elements" (read: numbers) have the same number of characters. You should split the strings so you can get the elements out of the result arrays instead:

    string JoinedWithComma1 = "8,1,6,3,16,9,14,11,24,17,22,19";
    string JoinedWithComma2 = "2,7,4,5,10,15,12,13,18,23,20,21";
    
    var split1 = JoinedWithComma1.Split(',');
    var split2 = JoinedWithComma2.Split(',');
    
    if (split1.Length != split2.Length)
    {
        // TODO: decide what you want to happen when the two strings
        //       have a different number of "elements".
        throw new Exception("Oops!");
    }
    

    Then, you can easily write a for loop to merge the two lists:

    var merged = new List<string>();
    for (int i = 0; i < split1.Length; i += 2)
    {
        if (i + 1 < split1.Length)
        {
            merged.AddRange(new[] { split1[i], split1[i + 1],
                                    split2[i], split2[i + 1] });
        }
        else
        {
            merged.AddRange(new[] { split1[i], split2[i] });
        }
    }
    
    string result = string.Join(",", merged);
    Console.WriteLine(
        result);      // 8,1,2,7,6,3,4,5,16,9,10,15,14,11,12,13,24,17,18,23,22,19,20,21
    

    Try it online.