'array of integer input from user
I have a question related to filling it in an array. In the program I have to write I am given "input from user: different number of numbers separated by space (for example: 1 4 6 2)". These numbers must be entered in an array that will be used later. The problem is the following how to insert in the array an indefinite number of numbers written on one line with space between them without determining their number in advance?
Solution 1:[1]
I think the easier thing to do would be to split input string by space and then use Linq to map each element to an int:
String userInput = "1 4 6 2";
int[] ints = userInput.Split(' ').Select(x => Int32.Parse(x)).ToArray();
Solution 2:[2]
this is the answer to my question. I wish I had helped someone.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Stack_Sum
{
class Program
{
static void Main(string[] args)
{
Stack<int> numbers = new Stack<int>();
string input = Console.ReadLine();
string[] number = Regex.Split(input, @"\D+");
foreach (string value in number)
{
if (!string.IsNullOrEmpty(value))
{
int i = int.Parse(value);
Console.WriteLine("Number: {0}", i);
}
}
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mureinik |
Solution 2 | ilian Dimitrov |