Tag Archives: string
Get value between two strings
You might find this snippet particular useful in cases where you want to get a value between two other values.
This takes advantage of the string’s Split
overload to pass an array of two values. This will result in the string being split twice, once for the first value in the array and once more for the second value. The result will be that the second value in the array that Split
returns is the actual value between the first and the second value we passed as argument.
Code:
1 2 3 4 5 6 7 8 9 10 11 | private string GetBetween(string strSource, string strStart, string strEnd) { string result = string.Empty; if (strSource.Contains(strStart) && strSource.Contains(strEnd)) { result = strSource.Split(new string[] { strStart, strEnd }, StringSplitOptions.None)[1]; } return result; } |
Example:
1 2 3 4 | string source = "this is (my value) a test"; // Returns "(my value)" GetBetween(source, "this is ", " a test"); |