Search code examples
c#cstringformatted-input

C# equivalent of C sscanf


Possible Duplicate:
Is there an equivalent to 'sscanf()' in .NET?

sscanf in C is a nice way to read well formatted input from a string.

How to achieve this C#.

For example,

int a,b;
char *str= "10 12";
sscanf(str,"%d %d",&a,&b);

The above code will assign 10 to a and 12 to b.

How to achieve the same using C#?


Solution

  • There is no direct equivalent in C#. Given the same task in C#, you could do it something like this:

    string str = "10 12";
    var parts = str.Split(' ');
    int a = Convert.ToInt32(parts[0]);
    int b = Convert.ToInt32(parts[1]);
    

    Depending on how well-formed you can assume the input to be, you might want to add some error checks.