2014-01-22 45 views
1

我有一个从控制台读取的矩阵。元素由空格和新行分隔。我怎样才能将它转换成C#中的多维int数组?我曾尝试过:将字符串转换为多维数组

String[][] matrix = (Console.ReadLine()).Split('\n').Select(t => t.Split(' ')).ToArray(); 

但是当我点击输入时,程序结束,它不允许我输入更多的行。

的示例是:第一

1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
5 6 7 8 9 
+0

什么语言这(将其添加到标签)是什么?你也只是阅读一行。 – Njol

+1

也许我已经远离控制台应用太久了,但是如何接受'Console.ReadLine'中的'\ n'?读取是否在'\ n'上终止? –

+0

@BradChristie - 在一个循环中接受多个'Console.ReadLine()' – Jamiec

回答

0

第一件事,Console.ReadLine()读取从输入的单行。所以为了接受多行,你需要做两件事:

  1. 有一个循环,允许用户继续输入数据行。你可以让他们走,直到他们留下一行空白,或者你可以修复它到5行输入
  2. 存储这些“行”的数据供将来处理。

假设用户可以输入任意数量的线,和一个空行(只是击中输入)指示的数据项是这样的结束就足够了

List<string> inputs = new List<string>(); 
var endInput = false; 
while(!endInput) 
{ 
    var currentInput = Console.ReadLine(); 
    if(String.IsNullOrWhitespace(currentInput)) 
    { 
     endInput = true; 
    } 
    else 
    { 
     inputs.Add(currentInput); 
    } 
} 

// when code continues here you have all the user's input in separate entries in "inputs" 

现在用于使该成阵列的阵列:

var result = inputs.Select(i => i.Split(' ').ToArray()).ToArray(); 

这将给你一个字符串数组的数组(这是你的例子)。如果你想这些是整数,你可以解析它们作为你去:

var result = inputs.Select(i => i.Split(' ').Select(v => int.Parse(v)).ToArray()).ToArray(); 
0
// incoming single-string matrix: 
String input = @"1 2 3 4 5 
2 3 4 5 6 
3 4 5 6 7 
4 5 6 7 8 
5 6 7 8 9"; 

// processing: 
String[][] result = input 
    // Divide in to rows by \n or \r (but remove empty entries) 
    .Split(new[]{ '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries) 
    // no divide each row into columns based on spaces 
    .Select(x => x.Split(new[]{ ' ' }, StringSplitOptions.RemoveEmptyEntries)) 
    // case from IEnumerable<String[]> to String[][] 
    .ToArray(); 

结果:

String[][] result = new string[]{ 
    new string[]{ "1","2","3","4","5" }, 
    new string[]{ "2","3","4","5","6" }, 
    new string[]{ "3","4","5","6","7" }, 
    new string[]{ "4","5","6","7","8" }, 
    new string[]{ "5","6","7","8","9" } 
}; 
0

它可以以多种方式

可以读取一个完成包含由char分隔的多个数字的行,由该char分隔,获得一个int数组,然后您应该获取一个矩阵。

使用开箱即用的linq,获取步骤没有微不足道的方法,我认为从LinuxLib或类似的代码复用器中使用第三方库并非如此。

0
int[,] Matrix = new int[n_rows,n_columns]; 


    for(int i=0;i<n_rows;i++){ 
     String input=Console.ReadLine(); 
     String[] inputs=input.Split(' '); 
     for(int j=0;j<n_columns;j++){ 
      Matrix[i,j]=Convert.ToInt32(inputs[j]); 
     } 
    } 

你可以试试这个加载矩阵