划分字符串列表
本文关键字:列表 字符串 划分 | 更新日期: 2023-09-27 18:35:55
不太
知道这个问题的标题,所以请随时编辑。
我有一个字符串列表,其中所有元素都是长度为 40 的字符串。我想做的是在字符 20 处拆分列表元素,并将现在分割的字符串的最后一部分推送到列表中的下一个元素,附加列表中的所有其他元素。
例如
list[0] = 0011
list[1] = 2233
list[2] = 4455
^split here
// new list results in:
list[0] = 00
list[1] = 11
list[3] = 22
list[4] = 33
list[5] = 44
list[6] = 55
如何实现这一点?
list = list.SelectMany(s => new [] { s.Substring(0, 20), s.Substring(20, 20) })
.ToList();
list = list.SelectMany(x=>new[]{x.Substring(0, 20), x.Substring(20)}).ToList();
不知道为什么要这样做,但使用 linq 非常简单:
List<string> split = list.SelectMany(s => new []{s.Substring(0, 2), s.Substring(2)}).ToList();
如果必须使用现有数组:
const int elementCount = 3;
const int indexToSplit = 2;
string[] list = new string[elementCount * 2] { "0011", "0022", "0033", null, null, null };
for (int i = elementCount; i > 0; --i)
{
var str = list[i-1];
var left = str.Substring( 0, indexToSplit );
var right = str.Substring( indexToSplit, str.Length - indexToSplit );
var rightIndex = i * 2 - 1;
list[rightIndex] = right;
list[rightIndex - 1] = left;
}
foreach( var str in list )
{
Console.WriteLine( str );
}