如何根据用户输入将数组划分为二维?

时间:2017-10-16 13:08:47

标签: c# arrays

我在这次大学演习中坚持了一个星期,我无法解决如何解决它。

练习包括用户编写单词并存储在数组中。然后,用户输入一个数字,程序根据用户数输入将单词数组划分为二维数组。

例如:用户写"Car", "Truck", "Motorbike", "Cat", "Dog", "Bird"。然后放"3",所以程序就这样做了:

["Car", "Truck", "Motorbike", "Cat", "Dog", "Bird"]

[["Car", "Truck", "Motorbike"] ["Cat", "Dog", "Bird"]]

如果用户输入4,则返回必须为:

[["Car", "Truck", "Motorbike", "Cat"] ["Dog", "Bird"]]

编辑:这是代码

using System;
using System.Collections;

namespace probando_separar_arrays {
    class Program {
        static void Main(string[] args) {
            int num, i = 0;
            String pos;
            ArrayList array = new ArrayList();
            do {
                Console.Write("Please write a word: ");
                pos = Console.ReadLine();
                array.Add(pos);
            } while (!int.TryParse(pos, out num));
            Console.WriteLine("The input words are: ");
            while (i < array.Count - 1) {
                Console.WriteLine(array[i]);
                i++;
            }
            /* Here is where I got stuck, cannot find a way to initialize the
             * Bidimensional array
             */
            Console.ReadKey();
        }
    }
}

2 个答案:

答案 0 :(得分:1)

尝试使用 Linq

using System.Linq;

...

// Let user input all the items in one go, e.g.
// Car, Truck, Motorbike, Cat, Dog, Bird
string[] source = Console
  .ReadLine()
  .Split(new char[] { ' ', '\t', ';', ',' }, StringSplitOptions.RemoveEmptyEntries);

// size of the line; 
// simplest approach (Parse); int.TryParse is a better choice
int n = int.Parse(Console.ReadLine());

// Let's create a jagged array with a help of modulo arithmetics:
//   source.Length / n + (source.Length % n == 0 ? 0 : 1) 
// we have "source.Length / n" complete lines and (possible) incomplete tail
string[][] result = Enumerable
  .Range(0, source.Length / n + (source.Length % n == 0 ? 0 : 1))
  .Select(index => source
     .Skip(n * index) // skip index lines (each n items long)
     .Take(n)         // take up to n items
     .ToArray())      // materialize as array 
  .ToArray();

// finally, let's join the jagged array (line by line) into a single string
string text = "[" + string.Join(" ", result
  .Select(line => $"[{string.Join(", ", line)}]")) + "]";

Console.WriteLine(text);

收入:

Car, Truck, Motorbike, Cat, Dog, Bird
4 

结果:

[[Car, Truck, Motorbike, Cat] [Dog, Bird]]

答案 1 :(得分:0)

这是一个符合你想要的通用方法:

public static T[][] SplitArray<T>(T[] array, int size) {
    // calculate how long the resulting array should be.
    var finalArraySize = array.Length / size + 
        (array.Length % size == 0 ? 0 : 1);
    var finalArray = new T[finalArraySize][];
    for (int i = 0 ; i < finalArraySize ; i++) {
        // Skip the elements we already took and take new elements
        var subArray = array.Skip(i * size).Take(size).ToArray(); // Take actually will return the rest of the array instead of throwing an exception when we try to take more than the array's elements
        finalArray[i] = subArray;
    }
    return finalArray;
}