string类提供了判断字符串B在字符串A中首次(或最后)出现的Index的方法,但有时候需要判断B在A中出现了多少次。
为此想了一个算法。
public static void CountIndexOf1(string A, string B,int startindex,ref int count)
{ int j= A.IndexOf(B,startindex);
if (j <= )
return;
count++;
CountIndexOf(A, B, j+test.Length,ref count);
}
当然,为了方便,可以简单修改一下直接把上述方法扩展到string类:
public static class Extend //Extend类不能是内部类
{
public static void CountIndexOf(this string A, string B, int startIndex, ref int count)
{ int j = A.IndexOf(B, startIndex);
if (j <= )
return;
count++;
A.CountIndexOf(B, j + B.Length, ref count);
}
}
好了,来测试一下(完整代码):
class Program
{
static void Main(string[] args)
{
int i = , j = ;
string test = "samssamdamfdkamcdcdafdsamamasm";
CountIndexOf1(test, "am", , ref i);//查找test中含有多少个"am"
test.CountIndexOf("am", , ref j);//string类的扩展方法
Console.WriteLine("CountIndexOf1方法测试:包含am{0}个,应该为6个", i);
Console.WriteLine("扩展方法测试:包含am{0}个,应该为6个", j);
Console.Read();
}
public static void CountIndexOf1(string A, string B, int startindex, ref int count)
{ int j = A.IndexOf(B, startindex);
if (j <= )
return;
count++;
CountIndexOf1(A, B, j + B.Length, ref count);
}
}
public static class Extend
{
public static void CountIndexOf(this string A, string B, int startIndex, ref int count)
{ int j = A.IndexOf(B, startIndex);
if (j <= )
return;
count++;
A.CountIndexOf(B, j + B.Length, ref count);
}
}
测试结果: