如何查找字符串C#

时间:2016-04-07 17:20:11

标签: c#

我有这个功能:

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);
    }
    else
    {
        return "";
    }
}

private void button9_Click(object sender, EventArgs e)
{
    string text = "This is an example string and my data1 is here and my data2 is and  my data3 is ";
    richtTextBox1.Text = getBetween(text, "my", "is");
}

该功能给了我这个结果:

enter image description here

我想要这个结果:

  

data1 data2 data3

1 个答案:

答案 0 :(得分:1)

你必须在循环中这样做:

public static string getBetween(string strSource, string strStart, string strEnd)
    {
        int Start = 0, End = 0;
        StringBuilder stb = new StringBuilder();

        while (strSource.IndexOf(strStart, Start) > 0 && strSource.IndexOf(strEnd, Start + 1) > 0)
        {
            Start = strSource.IndexOf(strStart, Start) + strStart.Length;
            End = strSource.IndexOf(strEnd, Start);
            stb.Append(strSource.Substring(Start, End - Start));

            Start++;
            End++;
        }

        return stb.ToString();
    }