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     }

    测试结果:

  • 相关阅读:
    springMVC和Struts2的区别
    Java并发教程(Oracle官方资料)
    Java并发教程(Oracle官方资料)
    Perl 按地区统计访问次数
    Perl 多个正则匹配
    Perl 判断字符串为空
    Java中的大小写字母相互转换(不利用Java自带的方法)
    如何利用JavaScript遍历JSON数组
    javax.servlet.JspTagException:Illegal use of -style tag without as its di
    PERL get网页
  • 原文地址:https://www.cnblogs.com/hellow-zili/p/3965281.html
Copyright © 2011-2022 走看看