gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:06:55 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com