Learning never exhausts the mind

Last Updated by

This useful code snippet will parse a string and return the contents between two tokens. This was originally used as a quick and dirty way to get the contents of an XML string, however it has found many other uses since.
public static string GetStringInBetween(string strBegin, string strEnd, string strSource, bool includeBegin, bool includeEnd)
{
    string[] result = {string.Empty, string.Empty};
    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[0];
}

Original author unknown.

Example Usage

string Example = "<startTag>Demo Text</startTag>";
string InBetween = GetStringInBetween("<startTag>", "</startTag>", Example, false, false)
Console.WriteLine(InBetween); // Outputs Demo Text

You can optionally include the start and end tags with the last two parameters.

2 thoughts on “Get String In Between Two Others with C#
  • 8th November 2015 at 12:00 am

    it cannot handle multiple text with the same tags, i made a program in python which is much easier, but struggling to translate to c#(im a c# newbie), please make it complete.. forsake

    Reply
  • 12th December 2014 at 12:00 am

    IT WORKED!!! Thanks a lot!

    Reply

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.