用递归法判断字符串A中包含多少个字符串B

Posted on   FanQH  阅读(823)  评论(0编辑  收藏  举报

 string类提供了判断字符串B在字符串A中首次(或最后)出现的Index的方法,但有时候需要判断B在A中出现了多少次。

为此想了一个算法。

复制代码
1  public static void CountIndexOf1(string  A, string B,int startindex,ref int count)
2         {
3             
4             int j= A.IndexOf(B,startindex);
5             if (j <= 0)
6                 return;
7             count++;
8             CountIndexOf(A, B, j+test.Length,ref count);
9         }
复制代码

当然,为了方便,可以简单修改一下直接把上述方法扩展到string类:

复制代码
 1  public static class Extend   //Extend类不能是内部类
 2        {
 3            public static void CountIndexOf(this string A, string B, int startIndex, ref int count)
 4            {
 5 
 6                int j = A.IndexOf(B, startIndex);
 7                if (j <= 0)
 8                    return;
 9                count++;
10                A.CountIndexOf(B, j + B.Length, ref count);
11            }
12        }
复制代码

好了,来测试一下(完整代码):

复制代码
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             int i = 0, j = 0;
 6             string test = "samssamdamfdkamcdcdafdsamamasm";
 7             CountIndexOf1(test, "am", 0, ref i);//查找test中含有多少个"am"
 8             test.CountIndexOf("am", 0, ref j);//string类的扩展方法
 9             Console.WriteLine("CountIndexOf1方法测试:包含am{0}个,应该为6个", i);
10             Console.WriteLine("扩展方法测试:包含am{0}个,应该为6个", j);
11             Console.Read();
12         }
13         public static void CountIndexOf1(string A, string B, int startindex, ref int count)
14         {
15 
16             int j = A.IndexOf(B, startindex);
17             if (j <= 0)
18                 return;
19             count++;
20             CountIndexOf1(A, B, j + B.Length, ref count);
21         }
22     }
23     public static class Extend
24     {
25         public static void CountIndexOf(this string A, string B, int startIndex, ref int count)
26         {
27 
28             int j = A.IndexOf(B, startIndex);
29             if (j <= 0)
30                 return;
31             count++;
32             A.CountIndexOf(B, j + B.Length, ref count);
33         }
34     }
复制代码

测试结果:

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
· 张高兴的大模型开发实战:(一)使用 Selenium 进行网页爬虫
点击右上角即可分享
微信分享提示