Normally in Python 2/3 we may use the following code to split two space-separated integers into two variables:
a,b = map(int,input().split())
Is there a short C# equivalent to this? (i.e nothing as long as below)
string[] template = Console.ReadLine().Split();
a = Convert.ToInt32(template[0]);
b = Convert.ToInt32(template[1]);
You could try this:
var result = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
However, the above code would crash if the input is not valid.
A more fault tolerant approach would be the following:
var result = Console.ReadLine()
.Split(' ')
.Select(input =>
{
int? output = null;
if(int.TryParse(input, out var parsed))
{
output = parsed;
}
return output;
})
.Where(x => x != null)
.Select(x=>x.Value)
.ToArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With