wrath1888 wrath1888 - 1 year ago 99
C# Question

c# Get numbers, booleans and strings from string

I have string type,name 2 doubles and 1 boolean in my string. Please help me with parsing it.

string type,name;
bool isChocolate;
double weight, price;
string line = "Candy Red Riding Hood,0.17,2.21,true";
if (line.ToLower().Contains("candy"))
type = "candy";
line = line.ToLower().Replace("candy", " ").Trim();
if (line.ToLower().Contains("true"))
isChocolate = true;
line = line.ToLower().Replace("true", " ").Trim();
else if(line.ToLower().Contains("false"))
line = line.ToLower().Replace("false", " ").Trim();

Then I get stuck. For me it doesn't matter which of 2 doubles will be a price and which - for weight.

Answer Source

You can use string.Split.

string line = "Candy Red Riding Hood,0.17,2.21,true";

var parts = line.Split(',');

string stringValue = parts[0];
double weight = double.Parse(parts[1], CultureInfo.InvariantCulture);
double price = double.Parse(parts[2], CultureInfo.InvariantCulture);
bool boolValue = Convert.ToBoolean(parts[3]);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download