-2

I have a question about parsing data in C#. I have a string that starts with the $ sign and ends with the $ sign and contains 5 different values that are separated by semicolons(','). An example is given below.

$value1,value2,value3,value4,value5$

How do I put each of these values in a variable?

Reza Dehghani
  • 15
  • 1
  • 6

4 Answers4

6

First of all, trim dollar ($) character from your input string and then split it by comma (,),

string str = "$value1,value2,value3,value4,value5$";

string[] values = str.Trim('$').Split(',');  //<= You can add ".ToArray()" at the end for your understaning.

Output: (From Debugger)

enter image description here

Then you can easily get each of your string in above array to separate string variable,

string value1 = values[0];
string value2 = values[1];
string value3 = values[2];
string value4 = values[3];
string value5 = values[4];

If your values are undetermined then you can simply use foreach loop to access each value like,

foreach(string value in values)
{
    //Do code with each value
} 
er-sho
  • 9,581
  • 2
  • 13
  • 26
2

Try something like this:

var str = "$value1,value2,value3,value4,value5$";
var arr = str.Replace("$", "").Split(',');
var s1 = arr[0];
...
var s5 = arr[4];
Art Drozdov
  • 157
  • 1
  • 11
0
string str = "$value1,value2,value3,value4,value5$";
str = str.Trim('$'); //removes the '$' characters
string[] array = str.Split(','); //creates an array containing 'value1', 'value2', 'value3', 'value4', 'value5'
elgaspar
  • 458
  • 3
  • 11
0

This could be a duplicate post but here is the quick answer.

string str = "$value1,value2,value3,value4,value5$";
string[] vals = str.Split(','); // splits the strings 
foreach(string value in vals)
{
  string parsedVal;
  if(value.Contains(',') // when split , commas will remain, if it exists we remove
  { 
    parsedVal = value.Trim(',');
  }
  else 
  {
    parsedVal = value;
  }
  //your value is assigned here
  //yourVal = parsedVal;
}