实现函数 int GetStrCount(string str1,string str2);
例如;str1:"abc" str2:"ab" 得到1
str1:"aaa" str2:"aa" 得到2,说白了就是str2在str1中出现的次数。我的代码:
Regex RegexWords = new Regex(str2);
int WordCount = RegexWords.Matches(str1).Count;但是在 str1:"aaa" str2:"aa"下还是得到1,好久没写正则了,忘了好多正则表达式regexstring
例如;str1:"abc" str2:"ab" 得到1
str1:"aaa" str2:"aa" 得到2,说白了就是str2在str1中出现的次数。我的代码:
Regex RegexWords = new Regex(str2);
int WordCount = RegexWords.Matches(str1).Count;但是在 str1:"aaa" str2:"aa"下还是得到1,好久没写正则了,忘了好多正则表达式regexstring
string str2 = "aa";
string pattern = @"(?is)(?=.*?" + str2 + ").";
int n = Regex.Matches(str1, pattern).Count;
因为正则表达式为了效率是顺序检测的,不会回溯,只有aaaa才可能用正则得到2.
---------------------------------------------------------------
str1 = "aa1aa", str2 = "aa";情况下你的代码得到的是4 ,正确应该是2
string str2 = "aa";
string pattern = @"(?is)(?!"+str2+").";
int n =str1.Length- Regex.Matches(str1, pattern).Count;
string s1 = "aaaa";
string s2 = "aa"; var count = s1.Select((x, i) => new { x, i }).Where(t => t.i <= s1.Length - b.Length && s1.Substring(t.i, b.Length) == s2).Count();
private int GetStrCount(string str1, string str2)
{
int len = str2.Length;
int count = 0;
for (int i = 0; i+len <= str1.Length; i++)
{
if (str1.Substring(i, len) == str2)
{
count++;
}
}
return count;
}
=======================================================
.NET快速开发整合框架(RDIFramework.NET),基于.NET的快速开发、整合框架,给用户和开发者最佳的.Net框架部署方案。
平台博客:[CNBLOGS]http://www.cnblogs.com/huyong
[CSDN]http://blog.csdn.net/chinahuyong
交流QQ:406590790 (请注明:CSDN)
平台微博:http://t.qq.com/yonghu86
邮件交流:[email protected]