-1

I have a instrument which returns me a string value as this

string var = "0,0,0.1987,22.13"; 

I want to use only the 4th value "22.13". I tried with Trim() and Replace() methods but couldn't exactly get what I want. How to achieve this?

Arghya C
  • 9,805
  • 2
  • 47
  • 66
Vasanth
  • 43
  • 1
  • 11
  • Duplicate of [Easiest way to parse a comma delimited string to some kind of object I can loop through to access the individual values?](http://stackoverflow.com/questions/2235683/easiest-way-to-parse-a-comma-delimited-string-to-some-kind-of-object-i-can-loop) – Bjørn-Roger Kringsjå Dec 02 '15 at 05:25

3 Answers3

6

The Split method is the best to use here!

The Split method does what it says on the lid. It splits a string into different parts at a character separator that you specify. e.g. "Hello World".Split(' ') splits the string into a string[] that contains {"Hello", "World"}.

So in this case, you can split the string by ',':

var.Split (',') //Use single quotes! It's of type char

If you want to access the fourth item, use an indexer! (of course)

var.Split(',')[3] //Remember to use 3 instead of 4! It's zero based!

Now you can happily store the string in some variable

string fourthThing = var.Split (',')[3];

Additional Information:

The Split method also has a overload that takes a char and a StringSplitOptions. If you do something like this:

var.Split (',', StringSplitOptions.RemoveEmptyEntries)

Empty entries will be automatically removed! How good!

More information: https://msdn.microsoft.com/en-us/library/system.string.split(v=vs.110).aspx

Sweeper
  • 213,210
  • 22
  • 193
  • 313
3

You can use string Split method

string data = "0,0,0.1987,22.13";
string value = data.Split(',')[3];
Arghya C
  • 9,805
  • 2
  • 47
  • 66
3

To pick up the last element, you can use Split function and Linq as below

string GetLastElement(string data) {
   return data.Split(',').Last();
}
Ankit Vijay
  • 3,752
  • 4
  • 30
  • 53