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?
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?
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
To pick up the last element, you can use Split function and Linq as below
string GetLastElement(string data) {
return data.Split(',').Last();
}