Home > Software design >  How to parse this single line Console input most efficiently
How to parse this single line Console input most efficiently

Time:05-05

I am trying to get the input from the user in a single Line with with [, ,] separators. Like this:

[Q,W,1] [R,T,3] [Y,U,9]

And then I will use these inputs in a function like this:

f.MyFunction('Q','W',1); // Third parameter will be taken as integer
f.MyFunction('R','T',3);
f.MyFunction('Y','U',9);

I thought I could do sth like:

    string input = Console.ReadLine();
    string input1 = input.Split(' ')[0];
    char   input2 = input.Trim(',') [0];

But it seems to repeat a lot. What would be the most logical way to do this?

CodePudding user response:

Sometimes a regular expression really is the best tool for the job. Use a pattern that matches the input pattern and use Regex.Matches to extract all the possible inputs:

var funcArgRE = new Regex(@"\[(.),(.),(\d )\]", RegexOptions.Compiled);

foreach (Match match in funcArgRE.Matches(input)) {
    var g = match.Groups;
    f.MyFunction(g[1].Value[0], g[2].Value[0], Int32.Parse(g[3].Value));
}

CodePudding user response:

Well, you could use LinQ to objects functions and do something like this:

var inputs = input.Split(' ')
    .Select(x =>
        x.Replace("[", "")
         .Replace("]", ""))
    .Select(x => new UserInput(x))
    .ToList();

foreach(var userInput in inputs)
{
   f.MyFunction(userInput.A, userInput.B, userInput.Number);
} 

// Somewhere else

public record UserInput
{
    public UserInput(string input)
    {
        //Do some kind of validation here and throw exception accordingly
        var parts = input.Split(',');

        A = parts[0][0];
        B = parts[1][0];
        Number = Convert.ToInt32(parts[2]);
    }

    public char A { get; init; }
    public char B { get; init; }
    public int Number { get; init; }
};

Or you could go further and implement "operator overloading" for the UserInput record and make it possible to implicitly convert from string to UserInput

  • Related