Wilson Wilson - 2 months ago 7x
C# Question

Find text in string with C#

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? Sorry this is pretty pseudo, but hopefully it makes sense.


Use this function.

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

How to use it:

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