I need to take the second line from string which starts from '\r' till the next '\r' character.
Here is an examle from my string
string str = "@b\r210.190\r\000.000\r\n";
I need to take value 210.190 but without '\r' characters inside.
I need to take the second line from string which starts from '\r' till the next '\r' character.
Here is an examle from my string
string str = "@b\r210.190\r\000.000\r\n";
I need to take value 210.190 but without '\r' characters inside.
Try using Split:
string str = "@b\r210.190\r\000.000\r\n";
string result = str
.Split(new char[] { '\r' }, 3) // split on 3 items at most
.Skip(1) // skip the 1st item
.FirstOrDefault(); // take the second item if exists (null if not)
Edit: In case of arbitrary strings (which can well be null or contain 1 billion characters) I suggest IndexOf and Substring (since Split creates an array which can be unwanted):
int from = str == null ? -1 : str.IndexOf('\r');
int length = from < 0 ? -1 : str.IndexOf('\r', from + 1) - from;
string result = length >= 0 ? str.Substring(from + 1, length) : null;
I also suggest to use the Split method, but I think that Dmitry Bychenko's answer could be phrased simpler:
string result = str.Split('\r')[1];
Here is an online demo: https://ideone.com/6Kedjj
As Dmitry Bychenko explained this may cause the creation of a long array even if you are only interested in the second item. This may be prevented by limiting the output to three matches:
string result = str.Split(new char[] {'\r'}, 3)[1];
The first parameter looks complicated but is in the same array of chars with just one element that is in fact used in the first version. (for completeness the updated demo: https://ideone.com/TimaHP)
You could also use Regex pattern matching for that. Method Regex.Match searches for first occurrence of the specified regular expression:
string str = "@b\r210.190\r\000.000\r\n";
var resultString = Regex.Match(str, @"(?<=\r).+?(?=\r)").Value;
Console.WriteLine(resultString + " " + resultString.Contains("\r"));
Output: 210.190 False