Question How to handle input containing white spaces?

dolle39

New member
Joined
Jul 13, 2015
Messages
1
Programming Experience
1-3
Let us assume that I want to read input, 2 integers from a user. What is the best way to handle the case when the user has entered a space before the first integer, for example: " 2 3"

If I do it like this:

C#:
Console.WriteLine("Enter 2 integers:");
string input = Console.ReadLine();
string[] tokens = input.Split(' ');
....
....

Then the size of tokens will be 3 since the first element in tokens will be "". I know I can just loop over the elements and ignore empty strings but is there some other better way of doing this?
 

JuggaloBrotha

Staff member
Joined
Apr 23, 2011
Messages
178
Location
Lansing, MI; USA
Programming Experience
10+
Use the StringSplitOptions.RemoveEmptyEntries option when splitting the string:
C#:
Console.WriteLine("Enter 2 integers:");
string input = Console.ReadLine();
string[] tokens = input.Split(' ', StringSplitOptions.RemoveEmptyEntries);
 
Top Bottom