BlueEyesSanDiego
BlueEyesSanDiego

Reputation: 1

C# use split to separate two parts of string

I have the following text in an Excel spreadsheet cell:

"Calories (kcal) "   

(minus quotes).

I can get the value of the cell into my code:

string nutrientLabel = dataRow[0].ToString().Trim();

I'm new to C# and need help in separating the "Calories" and "(kcal)" to to different variables that I can upload into my online system. I need the result to be two strings:

nutrientLabel = Calories
nutrientUOM = kcal

I've googled the hell out of this and found out how to make it work to separate them and display into Console.WriteLine but I need the values actually out to 2 variables.

foreach (DataRow dataRow in nutrientsdataTable.Rows)
{
    string nutrientLabel = dataRow[0].ToString().Trim();
}

char[] paraSeparator = new char[] { '(', ')' };
string[] result;

Console.WriteLine("=======================================");

Console.WriteLine("Para separated strings :\n");

result = nutrientLabel.Split(paraSeparator,
StringSplitOptions.RemoveEmptyEntries);

foreach (string str in result)
{
    Console.WriteLine(str);
}

Upvotes: 0

Views: 102

Answers (2)

nobody
nobody

Reputation: 11090

string [] s = dataRow[0].ToString().Split(' ');
nutrientLabel  = s[0];
nutrientUOM  = s[1].Replace(")","").Replace("(","");

Upvotes: 1

Rob
Rob

Reputation: 27367

You can use a simple regex for this:

var reg = new Regex(@"(?<calories>\d+)\s\((?<kcal>\d+)\)");

Which essentially says:

  1. Match at least one number and store it in the group 'calories'
  2. Match a space and an opening parenthesis
  3. Match at least one number and store it in the group 'kcal'
  4. Match a closing parenthesis

Then we can extract the results using the named groups:

var sampleInput = "15 (35)";
var match = reg.Match(sampleInput);
var calories = match.Groups["calories"];
var kcal = match.Groups["kcal"];

Note that calories and kcal are still strings here, you'll need to parse them into an integer (or decimal)

Upvotes: 1

Related Questions