假设我有两个字符串:
Hello,C#,Black,March
World,Java,White,April
我想将它们拆分并组合成一个数组(可能是二维数组)。 例如
{ "Hello", "World"}
{ "C#", "Java"}
{ "Black", "White"}
{ "March", "April" }
我的尝试:
string[] arr1 = str1.Split(',').Select(s => s.Trim()).ToArray();
string[] arr2 = str2.Split(',').Select(s => s.Trim()).ToArray();
if (arr1.Length == arr2.Length)
{
string[,] groupedValue = new string[arr1.Count(), arr2.Count()];
//groupedValue[0, 0] = ...
}
最佳答案
Linq 的使用 Zip在这里是有道理的:
string str1 = "Hello,C#,Black,March";
string str2 = "World,Java,White,April";
string[][] result = str1.Split(',')
.Zip(
str2.Split(','),
(s1, s2) => new string[] { s1, s2 }
)
.ToArray();
Zip()
迭代 Split()
的两个结果数组并为每个索引创建一个新数组 (s1, s2) => new string[] { s1, s2 }
包含当前索引的两个项目。
关于c# - 将字符串拆分为一组分组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113020/