Find text in string with C#

Wilson picture Wilson · May 22, 2012 · Viewed 461.4k times · Source

How can I find given text within a string? After that, I'd like to create a new string between that and something else. For instance, if the string was:

This is an example string and my data is here

And I want to create a string with whatever is between "my " and " is" how could I do that? This is pretty pseudo, but hopefully it makes sense.

Answer

Oscar Jara picture Oscar Jara · May 22, 2012

Use this method:

public static string getBetween(string strSource, string strStart, string strEnd)
{
    if (strSource.Contains(strStart) && strSource.Contains(strEnd))
    {
        int Start, End;
        Start = strSource.IndexOf(strStart, 0) + strStart.Length;
        End = strSource.IndexOf(strEnd, Start);
        return strSource.Substring(Start, End - Start);
    }

    return "";
}

How to use it:

string source = "This is an example string and my data is here";
string data = getBetween(source, "my", "is");