08-在字符串中统计子串出现的次数

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;
        }
    }
}
原文地址:https://www.cnblogs.com/zy-style/p/4315033.html