using System.Text.RegularExpressions;
/// <summary>
/// 計算字符串中子串出現的次數
/// </summary>
/// <param name="str">字符串</param>
/// <param name="substring">子串</param>
/// <returns>出現的次數</returns>
public static int SubstringCount(string str, string substring)
{
if (str.Contains(substring))
{
string strReplaced = str.Replace(substring, "");
return (str.Length - strReplaced.Length) / substring.Length;
}
return 0;
}
// 調用例子,這裡僅提供參考的思路
private void FindPosition()
{
sTemp="aabbccdd\r\naa3323\r\naa325sdf\r\n233asdf554\r\n"; // 這裡是原始字符串
int iCount = SubstringCount(sTemp, "\r\n"); // 這裡\r\n是分割符
if (iCount > 3)
{
Regex reg = new Regex("\r\n");
Match mat = reg.Match(sTemp);
int iCountTemp = 0;
while (mat.Success)
{
iCountTemp++;
//MessageBox.Show(mat.Index.ToString());//位置
if (iCountTemp > 20)
{
sTemp = sTemp.Substring(0, mat.Index);
break;
}
mat = reg.Match(sTemp, mat.Index + mat.Length);
}
}
}
摘自 keenweiwei的專欄