日期:2014-05-19  浏览次数:20881 次

如何计算字符串中指定字符串的个数?
对于一个字符串,如:str= "abcabcabcabc "
如何计算其中子串abc的个数,
我想了半天没想出来,请高手指点一个,
最好写出算法,
谢谢!

------解决方案--------------------
int count = 0;
int startIndex = 0;

while(startIndex <str.length)
{
startIndex = str.IndexOf( "abc ", startIndex );

if(startIndex <0)
break;

count++;

}

------解决方案--------------------
string str = "abcabaceabc ";
Regex regex = new Regex( "abc " );
int n = regex.Matches( str , 0 ).Count;
------解决方案--------------------
需要想半天!?两行代码就搞定了

string str = "abcabcabcabc ";
string temp = str.Replace( "abc ", " ");
int count = (str.Length - temp.Length) / 3;
Console.WriteLine( "字符串中abc的数量是: "+count);
------解决方案--------------------
Regex reg = new Regex(@ "abc ");
string s = "abcabcabc ";
this.TextBox1.Text = reg.Matches(s).Count.ToString();

---------------------------------------------
EMail:bdbox@163.com 请给我一个与您交流的机会!