Created
April 13, 2012 03:58
-
-
Save dalexsoto/2373563 to your computer and use it in GitHub Desktop.
C# function to get the string between 2 strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//This function gets the string between 2 strings | |
//Usage | |
string myString = "<span>Joe Smith</span>"; | |
string [] result = GetStringInBetween("<span>", "</span>", myString); | |
string output = result[0]; | |
string next = result[1]; | |
//Function | |
public static string[] GetStringInBetween(string strBegin, | |
string strEnd, string strSource, | |
bool includeBegin, bool includeEnd) | |
{ | |
string[] result ={ "", "" }; | |
int iIndexOfBegin = strSource.IndexOf(strBegin); | |
if (iIndexOfBegin != -1) | |
{ | |
// include the Begin string if desired | |
if (includeBegin) | |
iIndexOfBegin -= strBegin.Length; | |
strSource = strSource.Substring(iIndexOfBegin | |
+ strBegin.Length); | |
int iEnd = strSource.IndexOf(strEnd); | |
if (iEnd != -1) | |
{ | |
// include the End string if desired | |
if (includeEnd) | |
iEnd += strEnd.Length; | |
result[0] = strSource.Substring(0, iEnd); | |
// advance beyond this segment | |
if (iEnd + strEnd.Length < strSource.Length) | |
result[1] = strSource.Substring(iEnd | |
+ strEnd.Length); | |
} | |
} | |
else | |
// stay where we are | |
result[1] = strSource; | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment