首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

怎么计算字符串中指定字符串的个数

2012-01-31 
如何计算字符串中指定字符串的个数?对于一个字符串,如:str abcabcabcabc 如何计算其中子串abc的个数,我

如何计算字符串中指定字符串的个数?
对于一个字符串,如: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 请给我一个与您交流的机会!

热点排行