如何在c#中从字符串中生成矩阵
本文关键字:字符串 | 更新日期: 2023-09-27 18:17:22
我有一个字符串:string t = "{ { 1, 3, 23 } , { 5, 7, 9 } , { 44, 2, 3 } }"
我可以像这样使用字符串输入创建字符串矩阵吗?我不能简单地赋值:
int [ , ] matrix = t
是否有一些函数可以使用,或者我必须以某种方式拆分字符串?
PS: 't'字符串可以有不同数量的行和列。
这应该能达到你的目的
string t = "{ { 1, 3, 23 } , { 5, 7, 9 } , { 44, 2, 3 } }";
var cleanedRows = Regex.Split(t, @"}'s*,'s*{")
.Select(r => r.Replace("{", "").Replace("}", "").Trim())
.ToList();
var matrix = new int[cleanedRows.Count][];
for (var i = 0; i < cleanedRows.Count; i++)
{
var data = cleanedRows.ElementAt(i).Split(',');
matrix[i] = data.Select(c => int.Parse(c.Trim())).ToArray();
}
我想出了一些类似的东西,但有一些测试用例,你可能想要考虑-希望它有帮助:
private void Button_Click(object sender, RoutedEventArgs e)
{
int[][] matrix;
matrix = InitStringToMatrix("{ { 1, 3, 23 } , { 5, 7, 9 } , { 44, 2, 3 } }");
matrix = InitStringToMatrix("{ {0,1, 2 ,-3 ,4}, {0} }");
matrix = InitStringToMatrix("{} ");
matrix = InitStringToMatrix("{ {}, {1} } ");
matrix = InitStringToMatrix("{ { , 1,2,3} } ");
matrix = InitStringToMatrix("{ {1} ");
matrix = InitStringToMatrix("{ {1}{2}{3} }");
matrix = InitStringToMatrix(",,,");
matrix = InitStringToMatrix("{1 2 3}");
}
private int[][] InitStringToMatrix(string initString)
{
string[] rows = initString.Replace("}", "")
.Split('{')
.Where(s => !s.Trim().Equals(String.Empty))
.ToArray();
int [][] result = new int[rows.Count()][];
for (int i = 0; i < rows.Count(); i++)
{
result[i] = rows[i].Split(',')
.Where(s => !s.Trim().Equals(String.Empty))
.Select(val => int.Parse(val))
.ToArray();
}
return result;
}
如果你喜欢优化,这里有一个只有一个表达式的解决方案:
string text = "{ { 1, 3, 23 } , { 5, 7, 9 } , { 44, 2, 3 } }";
// remove spaces, makes parsing easier
text = text.Replace(" ", string.Empty) ;
var matrix =
// match groups
Regex.Matches(text, @"{('d+,?)+},?").Cast<Match>()
.Select (m =>
// match digits in a group
Regex.Matches(m.Groups[0].Value, @"'d+(?=,?)").Cast<Match>()
// parse digits into an array
.Select (ma => int.Parse(ma.Groups[0].Value)).ToArray())
// put everything into an array
.ToArray();
基于Arghya C的解决方案,这里是一个函数,返回int[,]
而不是int[][]
作为OP的要求。
public int[,] CreateMatrix(string s)
{
List<string> cleanedRows = Regex.Split(s, @"}'s*,'s*{")
.Select(r => r.Replace("{", "").Replace("}", "").Trim())
.ToList();
int[] columnsSize = cleanedRows.Select(x => x.Split(',').Length)
.Distinct()
.ToArray();
if (columnsSize.Length != 1)
throw new Exception("All columns must have the same size");
int[,] matrix = new int[cleanedRows.Count, columnsSize[0]];
string[] data;
for (int i = 0; i < cleanedRows.Count; i++)
{
data = cleanedRows[i].Split(',');
for (int j = 0; j < columnsSize[0]; j++)
{
matrix[i, j] = int.Parse(data[j].Trim());
}
}
return matrix;
}