How to get input separated by spaces

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

Example: 98 92 86 92 100 92 93

Spaces will be the only separator, and it will count 7 classes and store them in an array, but I'm not sure how to do this.

+4
source share
2 answers

Do not receive blank 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 
+2
source

Since you want to use Array , use the Split function.

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

or the best way to do this is with LINQ , which is automatically converted to an 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; 
+1
source

Source: https://habr.com/ru/post/1441117/


All Articles