Skip to content

Instantly share code, notes, and snippets.

@dalexsoto
Created April 13, 2012 03:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dalexsoto/2373563 to your computer and use it in GitHub Desktop.
Save dalexsoto/2373563 to your computer and use it in GitHub Desktop.
C# function to get the string between 2 strings
//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