wrath1888 wrath1888 - 12 days ago 5
C# Question

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.

L.B L.B
Answer

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]);