ExtensionMethod.NET Home of 875 C#, Visual Basic, F# and Javascript extension methods

GetStringInBetween

Get string in between two seprators

Source

public static string[] GetStringInBetween(this string strSource, string strBegin, string strEnd, 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;

    }
}

Example

string TestGetStringInBetween = "<h1>Hello Narender</h1>";
string[] result;
 result=TestGetStringInBetween.GetStringInBetween("<h1>", "</h1>", false, false);
Response.Write("<br /><br />StringInBetween is :" + result[0]);

Author: Narender Singh

Submitted on: 22 feb 2011

Language: C#

Type: System.StringSplitOptions

Views: 4466