C#检查一段文本中包含给定字符串的个数

最近在学C#,有时候遇到一些问题网上给的答案感觉不是很简练,又懒得去深入的找,所以自己有什么解决方法也贴一下记录下学习过程。

然后这次是一个简单的问题,检查一段文本中包含给定字符串的个数。很多人会说这种问题正则表达式不就解决了吗,但是...正则那些规则我老是记不清,于是就想用string提供的函数解决。

代码如下

using System;

using System.Collections.Generic;

namespace ConsoleApp1

{

class Program

{

    public static int CountStr(string str,string s)

    {

        int count = 0;

        while(str.Contains(s))

        {

            count += 1;

            str = str.Substring(str.IndexOf(s) + s.Length);

        }

        return count;

    }

    static void Main(string[] args)

    {

        string[] keys = { "Console", "static", "foreach", "int", "if" };

        #region STR

        string str = @"using System;using System.Collections.Generic;using System.Linq;

using System.Text;using System.Threading.Tasks;namespace ConsoleApp4{class Program{

public static void Test(List<int> L){Random rd = new Random();foreach (int item in L){Console.Write(item + '' );}

Console.WriteLine();for (int i = 0; i < L.Count; i++){if (L[i] == 5){L.Remove(L[i]);}}for (int i = 0; i < 3; i++)

{L.Insert(4, rd.Next(10));}for (int i = 0; i < L.Count; i++){if (L[i] == 1){L[i] = 10;}}foreach (int item in L){

Random rd = new Random();List<int> L = new List<int>();for(int i = 0; i < 20;i++){L.Add(rd.Next(10));}Test(L);Console.ReadKey();}}}";

        #endregion

        Dictionary<string, int> dict = new Dictionary<string, int>();

        for(int i = 0; i<keys.Length; i++)

        {

            int c = CountStr(str, keys[i]);

            dict.Add(keys[i], c);

        }

        foreach (KeyValuePair<string,int> item in dict)

        {

            Console.WriteLine($"\"{item.Key}\" ouccered {item.Value} times in this string.");

        }

        Console.ReadKey();

        }

    }

 }
结果

以上并未考虑性能问题,主要是搜索了一下发下没有和我思路差不多的觉得该简单记录一下。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。