利用C#编程计算某个字符在某个字符串中出现的次数

一、利用Replace(效率不高)

代码1:

string test = "good good study day day up";
string r = test.Replace("oo", "");
int num = (test.Length - r.Length)/2;
Console.WriteLine(num);

test = "good good study day day up";
r = test.Replace("o", "");
num = (test.Length - r.Length);
Console.WriteLine(num);

二、利用Split(效率最低)

test = "good good study day day up";

int i = test.Split('d').Length - 1;

代码3:

test = "good good study day day up";
int a = test.Split(new string[] { "oo" }, StringSplitOptions.None).Length - 1;

三、利用循环(效率高)

int c2 = 0;

for (int i = 0; i < test .Length; i++)

{

     if (test [i] == 'a')

     {

                    c2++;

      }

}

四、利用正则表达式

Regex rege = new Regex("o", RegexOptions.Compiled);

int count = rege.Matches(test).Count;

五、高效查找字符串出现次数

string str = "fecvcsdwfchkeov[page]ove283673ewekl[page]fsdh5d37op"; //被查的字符串
int count = 0; //计数器
string search = "[page]"; //要查的字符串
for (int i = 0; i < str.Length - search.Length; i++)
{
    if (str.Substring(i, search.Length) == search)
    {
      count++;
     }
}

六、IndexOf、While查找

string text = "今天下雪了吗,明天不会下雪了吧,什么时候才不下雪啊,我要去上学啊!";
string keyWord = "下雪";
int index = 0;
int count = 0;
while ((index = text.IndexOf(keyWord,index)) != -1)
{
count++;
Console.WriteLine("第{0}次;索引是{1}", count, index);
index = index + keyWord.Length;
}
Console.WriteLine("下雪出现的总次数:{0}", count);

七、foreach

int count;
string str="abcbabcbabbcabbabcccc";
foreach(char s in str)
{
  if(s=="a")
  {
     count++;
  }
}
console.write(count.tostring());

转载于:https://www.cnblogs.com/xyxy/p/4369585.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值