如何在c#中使用字符串制作矩阵

时间:2015-10-13 12:28:43

标签: c# string parsing matrix

我有字符串: if(data==0) //also check data first { alert("executed"); $(this).attr('style', 'Background-color:green;'); }

我可以像这样使用字符串输入制作字符串矩阵吗? 我不能简单地指定:

string t = "{  { 1, 3, 23 } ,  { 5, 7, 9 } ,  { 44, 2, 3 }  }"

我可以使用某些功能,还是以某种方式分割我的字符串?

PS:'t'字符串可以有不同数量的行和列。

4 个答案:

答案 0 :(得分:2)

这应该符合您的目的

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();
}

答案 1 :(得分:0)

我想出了一些相似的东西,但是你可能想要考虑一些测试用例 - 希望它有所帮助:

    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;
    }

答案 2 :(得分:0)

如果你喜欢优化,那么只有一个表达式的解决方案:

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();

答案 3 :(得分:0)

根据Arghya C's solution,这是一个函数,在OP询问时返回int[,]而不是int[][]

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;
}