[英]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"
. 格式为
"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. 我试图将ddl值(
345
)存储在单独的变量中,然后将其他数字存储在列表中。
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. 您可以尝试将字符串解析为ints,然后对要存储的任何其他值进行特殊检查。
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. *注意-这将比单循环执行效率低一些-但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]; 如果您不总是有3个数字,则ddl =然后是字符串myvalue = values.Split(',')[3];。 will not work.
不管用。 Theres a few easy ways around it like
有一些简单的方法可以解决
string myvalue = values.Split(',')[values1.Count() - 1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.