Shoxxer Shoxxer - 13 days ago 6
C# Question

Read input with different datatypes and space seperation

I'm trying to figure out how to write code to let the user input three values (string, int, int) in one line with space to separate the values.

I thought of doing it with String.Split Method but that only works if all the values have the same datatype.

How can I do it with different datatypes?

For example:
The user might want to input


Hello 23 54


I'm using console application C#

Answer

Well the first problem is that you need to decide whether the text the user enters itself can contain spaces. For example, is the following allowed?

Hello World, it's me 08 15

In that case, String.Split will not really be helpful.

What I'd try is using a regular expression. The following may serve as a starting point:

Match m = Regex.Match(input, @"^(?<text>.+) (?<num1>(\+|\-)?\d+) (?<num2>(\+|\-)?\d+)$");
if (m.Success)
{
    string stringValue = m.Groups["text"].Value;
    int num1 = Convert.ToInt32(m.Groups["num1"].Value);
    int num2 = Convert.ToInt32(m.Groups["num2"].Value);
}

BTW: The following part of your question makes me frown:

I thought of doing it with String.Split Method but that only works if all the values have the same datatype.

A string is always just a string. Whether it contains a text, your email-address or your bank account balance. It is always just a series of characters. The notion that the string contains a number is just your interpretation!

So from a program's point of view, the string you gave is a series of characters. And for splitting that it doesn't matter at all what the real semantics of the content are.

That's why the splitting part is separate from the conversion part. You need to tell your application that that the first part is a string, the second and third parts however are supposed to be numbers. That's what you need type conversions for.

Comments