user722226
user722226

Reputation: 179

How can you parse a string in C#?

We have a tricky puzzle to solve in developing a scoring component. We have a C# program where we get scores from an Oracle database in the format of

Fieldname

field value

We parse them into two comma delimited strings.

We have a requirement that when we get a fieldname like "LOW@HIGH" with a field value of "11@21" we want to put it into another variable in the format of LOW=11,HIGH=21.

Upvotes: 0

Views: 247

Answers (2)

Igor Pashchuk
Igor Pashchuk

Reputation: 2501

And an alternative, which introduces you to the very useful Zip extension method...

string Parse(string fieldName, string fieldValue)
{
  return string.Join( ",",
           fieldName.Split( '@' )
             .Zip( fieldValue.Split( '@' ),
               ( name, value ) => string.Concat( name, "=", value ) ) );
}

all validation checks are up to you...

Note that the method works if the "field name" field contains more than two field names. For example, field name "LOW@AVERAGE@HIGH" and field value "11@15@21" would give you LOW=11,AVERAGE=15,HIGH=21

It was a quick and fun exercise but I have to wonder why it's denormalized like this?!

Upvotes: 0

usr
usr

Reputation: 171246

First parse the input:

var parts = input.Split('@');
var i1 = int.Parse(parts[0]);
var i2 = int.Parse(parts[1]);

Next calculate the result:

return "LOW=" + i1 + ",HIGH=" + i2;

The problem becomes easy if you break it into these two steps.

Upvotes: 2

Related Questions