1

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.

3
  • 3
    I think you're going to have to build your own parser for that one. Commented Oct 13, 2015 at 12:31
  • Look into built-in Code generation library msdn.microsoft.com/en-us/library/… Commented Oct 13, 2015 at 12:33
  • Your example is of a 3x3 matrix. Is the matrix always square? Can it be jagged - meaning a row with 3, followed by a row with 2 ... etc? Commented Oct 13, 2015 at 13:25

4 Answers 4

2

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();
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.