我有 2 个带逗号的数字字符串:
8,1,6,3,16,9,14,11,24,17,22,19 和 2,7,4,5,10,15,12,13,18,23,20,21
我需要合并它们 或者每 N 个地方 (例如每获得第 4 名)
8,1,2,7,6,3,4,5,16,9,10,15,14,11,12,13,24,17,18,23,22,19,20,21
我已经检查了所有推荐的解决方案,但没有任何效果。
这是我目前的进展:
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];
}
感谢任何帮助。
您不能依赖字符串的长度或选择"第 i 个字符",因为并非所有"元素"(读取:数字)都具有相同数量的字符。您应该拆分字符串,以便可以从结果数组中获取元素:
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!");
}
然后,您可以轻松编写一个for
循环来合并两个列表:
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
在线试用。
如果你写一个正则表达式来得到一对数字:
var r = new Regex(@"d+,d+");
您可以将每个字符串分成一系列对:
var s1pairs = r.Matches(s1).Cast<Match>().Select(m => m.ToString());
var s2pairs = r.Matches(s2).Cast<Match>().Select(m => m.ToString());
您可以压缩序列
var zipped = s1pairs.Zip(s2pairs,(a,b)=>a+","+b);
并用逗号将位连接在一起
var result = string.Join(",", zipped);
它是如何工作的?
正则表达式匹配任意数量的数字,后跟逗号,后跟任意数量的数字
在一串
1,2,3,4,5,6
它匹配 3 次:
1,2
3,4
5,6
Matches
返回包含所有这些匹配项的MatchCollection
。若要与 LINQSelect
兼容,需要将MatchCollection
Cast
到IEnumerable<Match>
。之所以这样,是因为MatchCollection
早于IEnumerable<T>
的发明,因此枚举器返回需要强制转换的object
。一旦变成IEnumerable<Match>
,每个匹配都可以由一个Select
ToString
,产生一系列字符串,这些字符串是用逗号分隔的数字对。s1pairs
实际上是数字对的集合:
new []{ "1,2", "3,4", "5,6" }
对字符串 2 重复相同的操作
压缩序列。正如您可能从名称中想象的那样,Zip 从 A 中获取一个,然后从 B 中获取一个,然后从 A 中获取一个,然后从 B 中获取一个,将它们像衣服上的拉链一样合并,因此两个序列
new [] { "1,2", "3,4" }
new [] { "A,B", "C,D" }
当压缩结束时作为
new [] { "1,2,A,B", "3,4,C,D" }
剩下的就是用逗号将其连接在一起
"1,2,A,B,3,4,C,D"