2016-04-07 42 views
-5

我有這樣的功能:如何找到字符串中的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

+0

發佈的所有字符串的樣品** strSource,strStart,strEnd ** – rashfmnb

+0

請勿張貼您的代碼/鏈接屏幕截圖,而是用您的問題發佈實際的代碼。 – Habib

回答

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(); 
    } 
相關問題