JohnT
JohnT

Reputation: 77

How to make matrix from string in c#

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

Can I make a string matrix using string input like this? I can't simply assign:

int [ , ] matrix = t

Is there some function I could use or do I have to split my string in some way?

PS: 't' string could have various number of rows and columns.

Upvotes: 1

Views: 1929

Answers (4)

Arthur Rey
Arthur Rey

Reputation: 3058

Based on Arghya C's solution, here is a function which returns a int[,] instead of a int[][] as the OP asked.

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

Upvotes: 0

t3chb0t
t3chb0t

Reputation: 18685

If you like optimizations here's a solution with only one expression:

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

Upvotes: 0

Hugh Jones
Hugh Jones

Reputation: 2694

I came up with something rather similar but with some test cases you might want to think about - hope it helps :

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

Upvotes: 0

Arghya C
Arghya C

Reputation: 10078

This should serve your purpose

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

Upvotes: 2

Related Questions