思路:设字符串长度为m,子串长度为n。从字符串第i[0<=i<=m-n]个字符开始检测从第i个字符及其之后的n个字符组成的子串是否与指定子串相等,若相等则次数+1
namespace Pro1
{
class Program
{
//检测匹配次数的函数
static int SearchCount(string str, string sub)
{
int count = 0;
//只用检测到第str.Length-sub.Length个字符,因为之后的字符长度无法组成长度为sub.Length的子串
for(int i = 0; i < str.Length - sub.Length + 1; i++)
if (str[i] == sub[0])
if (str.Substring(i, sub.Length).Equals(sub))
count++;
return count;
}
static void Main(string[] args)
{
string str, substr;
Console.WriteLine("\r\nPlease input the string: ");
str = Console.ReadLine();
Console.WriteLine("\r\nPlease input the substring: ");
substr = Console.ReadLine();
Console.WriteLine("\r\nOccurrences: {0}\r\n", SearchCount(str.ToLower(), substr.ToLower()));
Console.ReadKey();
}
}
}