Tracey T. Winton
Tracey T. Winton

Reputation: 28

C#, parsing multiple numbers on the same line

If I got a line like this:

6 3 3 3 33 3 3 3 3 7 2 1 1 1 11 1 1 1 13 2 2 1 1 1 1 1 1 21 1 2 2

How would I parse this into a int array in C#? The thing is I don't have a determinate amount of numbers and specific amount of digits to parse.

Upvotes: 0

Views: 685

Answers (3)

Pranav Negandhi
Pranav Negandhi

Reputation: 1624

Begin with digging up the String.Split API call, followed by type casting to convert strings to numbers.

http://msdn.microsoft.com/en-us/library/ms228388.aspx is a good starting point.

Upvotes: 0

Darren
Darren

Reputation: 70728

You could use Split:

string test = "A B C D E F G";
var array = test.Split(' ');

Upvotes: 3

Andrei
Andrei

Reputation: 56688

string numbersString = "6 3 3 3 33 3 3 3 3 7 2 1 1 1 11 1 1 1 13 2 2 1 1 1 1 1 1 21 1 2 2";
var numbers = numbersString.Split().Select(token => int.Parse(token)).ToArray();

That is assuming all your numbers fall into integer range.

Update. And of course that will only work if each string part represents a valid integer - otherwise int.Parse will fall.

Upvotes: 7

Related Questions