Reputation: 2261
I have a string that I am trying to parse the values from. It is in this format "43,56,12,ddl=345"
.
I am trying to store the ddl value (345
) in a separate variable, then the other numbers in a list.
List<int> nums = new List<int>();
int? ddlValue;
How do I go about this?
Upvotes: 0
Views: 107
Reputation: 1033
I mean the simplest way is a split and replace.
string values = "43,56,12,ddl=345";
string[] values1 = values.Split(',');
foreach (var x in values1)
{
list.Add(x);
}
string myvalue = values.Split(',')[3];
myvalue = myvalue.Replace("ddl=","");
this assumes your going to be getting the same format every time. Maybe more information?
EDIT-
If you will not always have 3 numbers then the ddl= then string myvalue = values.Split(',')[3]; will not work. Theres a few easy ways around it like
string myvalue = values.Split(',')[values1.Count() - 1]
Upvotes: -1
Reputation: 7973
You can do something like this:
List<int> nums=new List<int>();
int intVariable = 0;
string s = "43,56,12,ddl=345";
string[] split=s.Split(',');
Regex regex = new Regex(@"^\d+$");
foreach(var element in split)
if(regex.IsMatch(element))
nums.Add(Convert.ToInt32(element));
else
{
intVariable = element.Split("=")[1];
}
Upvotes: 0
Reputation: 19646
You can do:
var sNums = "43,56,12,ddl=345".Split(',');
var ddl = int.Parse(sNums.First(s => s.Contains("ddl")).Replace("ddl=", ""));
var numbers = sNums.Where(s => !s.Contains("ddl")).Select(int.Parse);
*note - this will be slightly less efficient that doing it in a single loop - but more readable IMO.
Upvotes: 1
Reputation: 12979
You could try parsing the string for ints, and then have special checks for any other values you want to store.
var sNums = "43,56,12,ddl=345";
List<int> nums = new List<int>();
int? ddlValue;
foreach (var t in sNums.Split(',')) {
int u;
if (int.TryParse(t, out u)) {
nums.Add(u);
} else {
ddlValue = t.Split("=")[1];
}
}
Upvotes: 5