Home > Net >  Merge 2 Numeric strings with commas Alternatively every 4th place
Merge 2 Numeric strings with commas Alternatively every 4th place

Time:03-18

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 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.

CodePudding user response:

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.

CodePudding user response:

If you write a regular expression to get you a pair of numbers:

var r = new Regex(@"\d ,\d ");

You can break each string into a sequence of pairs:

var s1pairs = r.Matches(s1).Cast<Match>().Select(m => m.ToString());
var s2pairs = r.Matches(s2).Cast<Match>().Select(m => m.ToString());

And you can zip the sequences

var zipped = s1pairs.Zip(s2pairs);

And join the bits together with commas

var result = string.Join(",", zipped);
  • Related