using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace _05在字符串中統計子串出現的次數 { class Program { static void Main(string[] args) { int count = SubstringCount("qhwerzdfrefysasefhzylmjyfzhy723hzy84hd63", "hzy");//通常方法 //int count = RegexCount("qhwerzdfrefysasefhzylmjyfzhy723hzy84hd63");//正則方法 Console.WriteLine(count); Console.ReadKey(); } 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; } static int RegexCount(string str) { string regStr = "(hzy)"; MatchCollection matchs = Regex.Matches(str, regStr); return matchs.Count; } } }