制作一个矩阵

时间:2015-11-07 21:57:36

标签: c# string parsing matrix

这就是我想要做的事情:

编写一个C#程序,解析像A = A = [5 4 1; 3 6 1;产生m> = 2行且n> = 1列的矩阵A的2 3 9]。

我知道如何通过一次输入单个整数来创建矩阵,但我不知道如何读取它就像这样A = [5 4 1; 3 6 1; 2 3 9]并从中创建一个矩阵。 我正在撞墙。我不知道如何以这种方式使用解析。我需要一些建议和意见。

我做了类似的事情:

        string x;
        int m;
        int n;

        Console.WriteLine("Enter two no's seperated by space: ");

        x = Console.ReadLine();
        m = Convert.ToInt32(x.Split(' ')[0]);
        n = Convert.ToInt32(x.Split(' ')[1]);

        Console.WriteLine("" + m + " " + n);

但解析会在哪里发挥作用?

编辑: 我错误地解析了什么?是string.split解析吗?

编辑: 我尝试使用他们在msdn上的代码:它使用foreach并将每个元素放在不同的行上。我怎么把它变成3x3矩阵格式?

    char[] delimiterChars = { ' ', ',', '.', ':', '\t' ,'[' ,']', ';', '"', 'A', '=' };

    string text = "A = [5 4 1; 3 6 1; 2 3 9]";
    System.Console.WriteLine("Original text: '{0}'", text);

    string[] words = text.Split(delimiterChars);
    System.Console.WriteLine("{0} words in text:", words.Length);

    foreach (string element in words)
    {
        System.Console.WriteLine(element);
    }

    // Keep the console window open in debug mode.
    System.Console.WriteLine("Press any key to exit.");
    System.Console.ReadKey();

1 个答案:

答案 0 :(得分:0)

一个小正则表达式,字符串与Linq分开

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "A = [5 4 1; 3 6 1; 2 3 9]";

            string pattern = @"(?'name'\w+)\s+=\s+\[(?'numbers'[^\]]+)\]";
            Match match = Regex.Match(input, pattern);
            string name = match.Groups["name"].Value;

            string numbers = match.Groups["numbers"].Value;

            List<List<int>> array = numbers.Split(new char[] { ';' }).Select(x => x.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(z => int.Parse(z)).ToList()).ToList();
        }
    }
}
​
相关问题