Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift elements in string array to left to fill 'holes'

I have a list of names and phone numbers like so:

var phonelist = List<string[]> 
{
     new string[] {"Bill", "1234", "12345", "12314" },
     new string[] {"Bob", "", "12345", "12314" },
     new string[] {"Chris", "", "", "12314" },
     new string[] {"Dave", "1234", "", "12314" },
     new string[] {"Andy", "1234", "12345", "" },
}

What is the most efficient/elegant way to process this list so that the 'empty' numbers get filled from the right ?

Note, the arrays should stay the same length, like so:

var phonelist = List<string[]> 
{
     new string[] {"Bill", "1234", "12345", "12314" },
     new string[] {"Bob", "12345", "12314", "" },
     new string[] {"Chris", "12314", "", "" },
     new string[] {"Dave", "1234", "12314", "" },
     new string[] {"Andy", "1234", "12345", "" },
}
like image 856
Benjol Avatar asked Apr 28 '26 04:04

Benjol


1 Answers

for each array cell, check if its empty and swap it with cell+1, if it's still empty swap it with cell+2.. when cell becomes not empty do the same thing with cell+2...

    int j;

    foreach (string[] strs in phoneList)
    {
        for (int i = 0; i < strs.Length; i++)
        {
            j = 1;
            while (string.IsNullOrEmpty(strs[i]) && j < strs.Length - i)
            {
                if (!string.IsNullOrEmpty(strs[i + j])) // to not swap 2 empty strings
                {
                    strs[i] = strs[i + j];
                    strs[i + j] = "";
                }
                j++;
            }
        }
    }
like image 150
manji Avatar answered Apr 29 '26 20:04

manji



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!