1

I have a Console.ReadLine(); and I input 1 2 3 with spaces between. Then I want the numbers to be saved in an array like this {1,2,3} basically I want to take the spaces and tell c# to make them Index seperators.

anyvar = Convert.ToInt32(Console.ReadLine());
Int[] arrayvar = {}; 
Console.WriteLine(arrayvar[1]); // expects 2 
EpicKip
  • 4,015
  • 1
  • 20
  • 37
FlayerDev
  • 13
  • 3
  • 1
    Does this answer your question? [C# Splitting Strings?](https://stackoverflow.com/questions/7559121/c-sharp-splitting-strings) – Ryan Sparks Jan 02 '20 at 11:16
  • 1
    Take the string input, do `.Split( ' ' )` to get an array of the numbers split by space and `.Select( x => Convert.ToInt32( x ) ).ToArray()` to get an array of actual numbers. I suggest trying `int.TryParse` instead of `Convert.ToInt32` as someone could enter anything in the console – EpicKip Jan 02 '20 at 11:16
  • Does this answer your question? [How to split() a delimited string to a List](https://stackoverflow.com/questions/9263695/how-to-split-a-delimited-string-to-a-liststring) – Max Zolotenko Jan 02 '20 at 11:17

2 Answers2

0

This should do it

// Set array elements from Command Line by splitting the Command Line and parsing to Int 
var anyvar = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();

// Display the array elements using the array index     
Console.WriteLine(anyvar[1]);
Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32
  • btw does it work for lists and dictionaries , just asking – FlayerDev Jan 02 '20 at 13:02
  • @BDGGR_Flayer It can very well work for the `List` by chnaging the above code as `Console.ReadLine().Split(' ').Select(int.Parse).ToList();`. However Dictionary is a data structure based on key value pair you need to specify a key and then a value for that key, In which format will you be passing the data to be stored in a dictionary – Shahid Manzoor Bhat Jan 02 '20 at 13:09
0

You can try this way, live demo here

using System;
using System.Linq;

public class Program
{
    public static void Main()
    {
        var anyvar = "1 2 3";
        int[] arrayvar = anyvar.Split(' ').Select(Int32.Parse).ToArray(); 
        Console.WriteLine(arrayvar[1]); // expects 2 
    }
}
Nguyễn Văn Phong
  • 13,506
  • 17
  • 39
  • 56