我有两个数字字符串和逗号:
8,1,6,3,16,9,14,11,24,17,22,19和2,7,4,5,10,15,12,13,18,23,20,21
我需要将它们交替合并,每排第9位(例如,每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];
}
感谢你的帮助。
发布于 2022-03-18 06:33:24
如果您编写一个正则表达式以获得一对数字:
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);
它怎麽工作?
Regex匹配任意数量的数字,后面是逗号,后面是任意数量的数字。
一串串
1,2,3,4,5,6
它匹配3次:
1,2
3,4
5,6
Matches
返回包含所有这些匹配的MatchCollection
。要与LINQ Select
兼容,需要将Cast
MatchCollection
转换为IEnumerable<Match>
。这是因为MatchCollection
早于IEnumerable<T>
的发明,所以它的枚举器返回需要转换的object
s。一旦转换成IEnumerable<Match>
,每个匹配都可以由Select
生成一个字符串序列,这些字符串是由逗号分隔的数字对。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"
https://stackoverflow.com/questions/71521836
复制相似问题