简体   繁体   中英

C#: How to split multiple strings into 2D array?

I want to create a matrix from users input where each row is created from string of numbers divided by space. (In the beginning user inputs size of a matrix).

Example input:
1 4 6 4 enter
9 8 5 2 enter
0 3 6 1 enter

And the output will be: array[1, 1] = 1 array[1,2] = 4... array[2,1] = 9 etc.

Thanks in advance!

Easy way to do this would be to

  1. read the input
  2. Split the input based on spaces
  3. Convert it to list of int and add it to a List<List<int>> object.

Example: this code is very basic and assumes the input is going to be based on integers and spaces. You should look into adding checks to make sure input is in the correct format

List<List<int>> arr = new List<List<int>>();
while (true) {
    string line = Console.ReadLine();
    if (string.IsNullOrEmpty(line))
        break;
    arr.Add(line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToList());
}

// input:
1 2 3<enter>
4 5 6<enter>
7 8 9<enter>
<enter>

Or you can create a jagged array to access via indecies. Following assumes 3 rows.

int[][] arr = new int[3][];
int i = 0;
while (true) {
    string line = Console.ReadLine();
    if (string.IsNullOrEmpty(line))
        break;
    arr[i++] = line.Split(' ', StringSplitOptions.RemoveEmptyEntries).Select(x => int.Parse(x)).ToArray();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM