4

I want to try and get a line of numbers and count them and store them in an array. I want to have the user input numbers up to 100 and I want the program to be able to separate them by spaces and count them in C#

Example: 98 92 86 92 100 92 93

The spaces will be the only separator and it would count 7 grades and store them in an array but I'm not sure how to to really do this.

Skynet
  • 92
  • 2
  • 8
  • 1
    this is a real response: http://stackoverflow.com/questions/28070113/read-numbers-from-the-console-given-in-a-single-line-separated-by-a-space – Harry Sarshogh May 19 '15 at 04:33

2 Answers2

2

Not to get empty entries in case of 2 spaces

var ints = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)
                     .Select(i => int.Parse(i))
                     .ToList(); //or ToArray() whichever you want
L.B
  • 114,136
  • 19
  • 178
  • 224
1

Since you want an Array on this, use Split function.

string x = "98 92 86 92 100 92 93";
string[] val = x.Split(' ');
int totalCount = val.Length;

or a better way to do this is by using LINQ which automatically converts into array of integers

string x = "98 92 86 92 100 92 93";
int[] y = x.Split(' ').Select(n => Convert.ToInt32(n)).ToArray();
int totalCount = y.Length;
John Woo
  • 258,903
  • 69
  • 498
  • 492