Web Design that taps into the haromny and vision of your dreams.

Get String In Between Two Others with C#

By on in Coding

151 words, estimated reading time 1 minutes.

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.

Last updated on: Wednesday 21st June 2017

 

Comments

Have a question or suggestion? Please leave a comment to start the discussion.

king

king

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 to king
Claudiu Harn

Claudiu Harn

IT WORKED!!! Thanks a lot!

Reply to Claudiu Harn

 

Leave a Reply

Please keep in mind that all comments are moderated according to our privacy policy, and all links are nofollow. Do NOT use keywords in the name field. Let's have a personal and meaningful conversation.

Your email address will not be published.