标签:count good C# 编程 int Length test 某个 day
一、利用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());
标签:count,good,C#,编程,int,Length,test,某个,day 来源: https://www.cnblogs.com/cxd4321/p/15088715.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。