简体   繁体   English

如何从字符串中分离整数值并将其存储到C#中的变量中

[英]how to seperate integer values from a string and store it into a variable in C#

I am trying to get battery voltage using a micro controller which is returning value like this: 我正在尝试使用微控制器获取电池电压,该微控制器返回的值是这样的:

1,1.93 1,1.93

So I have to separate this 1,1.93 value from this string and store it into a variable. 因此,我必须将此1,1.93值与此字符串分开,并将其存储到变量中。 I have used "REGEX" and "SPLIT" but both are returning 我用过“ REGEX”和“ SPLIT”,但是都返回了

1 1
1 1
93 93

how could i get it like 1,1.93 我怎么能得到像1.1.93

private void button1_Click_1(object sender, EventArgs e)
{
    WebRequest req = WebRequest.Create("http://192.168.27.123/Command=dvsync");
    WebResponse res = req.GetResponse();
    StreamReader rd = new StreamReader(res.GetResponseStream(), Encoding.ASCII);
    String val4 = (rd.ReadToEnd());
    textBox3.Text = val4;
    MessageBox.Show("Value" + val4);

}

在此处输入图片说明

在此处输入图片说明

if it is between the opening and closing <html> tags you can use the Split method the following way: 如果它在<html>标记之间,则可以通过以下方式使用Split方法:

string test = "<!DOCTYPE HTML><html>1,1.93</html>";

string [] res = test.Split(new string[] {"<html>", "</html>"}, StringSplitOptions.RemoveEmptyEntries);

string number = res[1];

Converting your input to double values requires parsing or your recevied data which can be done using the XElement. 将输入转换为双精度值需要解析或获取数据,可以使用XElement来完成。 Then split and convert the values using the InvariantCulture. 然后使用InvariantCulture拆分并转换值。

string received = "<!DOCTYPE HTML><html>1,1.93</html>";
string parsedValue = XElement.Parse(received).Value;
double[] values = Array.ConvertAll(parsedValue.Split(','), v => double.Parse(v, CultureInfo.InvariantCulture));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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