简体   繁体   中英

find and parse values from string

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?

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

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.

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM