c# - 将字符串数组中的元素向左移动以填充 'holes'

标签 c# algorithm arrays

我有一个姓名和电话号码列表,如下所示:

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", "" },
}

处理此列表以便从右侧填充“空”数字的最有效/最优雅的方法是什么?

请注意,数组应保持相同的长度,如下所示:

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", "" },
}

最佳答案

对于每个数组单元格,检查它是否为空并将其与 cell+1 交换,如果它仍然为空则将其与 cell+2 交换。当单元格不为空时对 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++;
            }
        }
    }

关于c# - 将字符串数组中的元素向左移动以填充 'holes',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1372235/

相关文章:

c# - LINQ 查询从 SQL 转换而来,它使用包含 GROUP BY 和 COUNT 的子查询

c# - ToDouble() 不工作?

algorithm - k近邻算法应该使用数字0-9的二值图像的哪些特征?

c# - 复制一个数组并将其存储在另一个数组中

php - 使用 mysql 和 php 选择以相同 4 位数字结尾的行进行分组

与 Net Framework 2.0 兼容的 C# JSON Rest 客户端

c# - PostBack 后 ASP.NET TextBox 值未保留 - session 值正常

algorithm - 二叉搜索树用于查找多个对象

python - python中的矩阵 split 和乘法

c# 在 FTP 服务器中上传一个 byte[]