-4

I want to split below string and need to read only values and store in some float variable kindly help how i can do that

string s = "PH_Value:7.539999961853027,Nitrate:1.0099999904632568,DO:10.229999542236328,Conductivity:6777.990234375,TSS:43.65999984741211";
Mong Zhu
  • 23,309
  • 10
  • 44
  • 76
Vinit
  • 1
  • 4
    post the you tried so far ? – Sund'er Sep 08 '22 at 05:31
  • 1
    hi and welcome to StackOverflow. I suggest to research: "C# split string by separator" and "C# convert string to float" This should get you to all the hundreds of StackOverflow posts that show how to solve these problems. – Mong Zhu Sep 08 '22 at 06:13

2 Answers2

1

Give this a go, next time try to attempt it yourself:

List<float> results = new List<float>();
Dictionary<string, float> dictResults = new Dictionary<string, float>();
string s = "PH_Value:7.539999961853027,Nitrate:1.0099999904632568,DO:10.229999542236328,Conductivity:6777.990234375,TSS:43.65999984741211";

string[] arr = s.Split(',');
foreach(string item in arr)
{
    string[] subArr = item.Split(':');
    results.Add(subArr[1]); //a list
    dictResults.Add(subArr[0],subArr[1]); // a dictionary for easy lookup
}
Jeremy Thompson
  • 61,933
  • 36
  • 195
  • 321
  • you forgot to convert the string from `subArr[1]` to float – Mong Zhu Sep 08 '22 at 06:58
  • Yes i am getting same error CS1503: Argument 1: cannot convert from 'string' to 'float' can you please help to solve that – Vinit Sep 08 '22 at 07:22
  • 1
    @Vinit to be honest mate, you need to learn how to research such stuff on the internet. take you favourite search engine and type in: "C# cannot convert from 'string' to 'float' " and you will find the answer to this problem on StackOverflow. I promise you that :) – Mong Zhu Sep 08 '22 at 08:22
  • Sorry guys I wrote the code off the top of my head. Yes `Convert.To` will do the trick feel free to edit or look up a plethora of other solutions. – Jeremy Thompson Sep 08 '22 at 08:55
  • @MongZhu i tried to find string to float conversion but i could not able to find it since i am new to programming if you guide me for this conversion – Vinit Sep 08 '22 at 11:39
  • @Vinit [there you go](https://stackoverflow.com/a/11202760/5174469) – Mong Zhu Sep 09 '22 at 07:07
0

You can try this :

string s = "PH_Value:7.539999961853027,Nitrate:1.0099999904632568,DO:10.229999542236328,Conductivity:6777.990234375,TSS:43.65999984741211";
List<double> values = new List<double>();
values = Regex.Matches(s, @"\d+\.*\d*").Cast<Match>().Select(m => double.Parse(m.Value)).ToList();
Md. Suman Kabir
  • 5,243
  • 5
  • 25
  • 43