C#统计N个相同子字符串的个数及位置
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的专栏
补充:软件开发 , C# ,