zoukankan      html  css  js  c++  java
  • 用递归法判断字符串A中包含多少个字符串B

     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     }

    测试结果:

  • 相关阅读:
    新安装的Apache和php,测试可以解析phpinfo,但是无法打开drupal网站
    Drupal7安装注意事项
    drupal7 为视图添加 过滤标准 内容类型
    Drupal网站报错:PDOException: in lock_may_be_available()
    窗口聚合函数与分组聚合函数的异同
    Linux环境下段错误的产生原因及调试方法小结(转)
    gzip 所使用压缩算法的基本原理(选摘)
    InfluxDB使用纪录
    子网掩码解释(转)
    列存的压缩原理学习
  • 原文地址:https://www.cnblogs.com/hellow-zili/p/3965281.html
Copyright © 2011-2022 走看看