题目:在给定的语句中,统计出指定字符串出现的次数。
例如:今天天气好晴朗处处好风光,今天天气好,今天天气好今天好天气,今天天天好天气 。
请统计出"今天"出现的次数。
主要方法有:
class Program
{ //在给定的语句中,统计出指定字符串出现的次数。
//例如:今天天气好晴朗处处好风光,今天天气好,今天天气好今天好天气,今天天天好天气 。
//请统计出"今天"出现的次数。
static void Main(string[] args)
{
#region 方法1:用Replace和Split
string strContent = "今天天气好晴朗处处好风光,今天天气好,今天天气好今天好天气,今天天天好天气";
//字符串替换
string strNewContent = strContent.Replace("今天", "@");
//字符串分割
string[] count = strNewContent.Split('@');
//该字符串出现的次数就是分割的片段数减1。
int times = count.Length - 1;
Console.WriteLine("\"今天\"出现的次数为{0}次", times);
Console.ReadKey();
#endregion
#region 方法2:用IndexOf
string strContent = "今天天气好晴朗处处好风光,今天天气好,今天天气好今天好天气,今天天天好天气";
string keyWords = "今天";
int index = 0;//索引位置
int count = 0; //统计次数
while ((index = strContent.IndexOf(keyWords, index)) != -1)
{
count++;
index = index + keyWords.Length;
}
Console.WriteLine("\"今天\"出现的次数为{0}次", count);
Console.ReadKey();
#endregion
#region 方法3:用正则表达式
string strContent = "今天天气好晴朗处处好风光,今天天气好,今天天气好今天好天气,今天天天好天气";
string keyWords = "今天";
//正则表达式匹配模式
int count = (Regex.Matches(strContent, keyWords)).Count;
Console.WriteLine("\"今天\"出现的次数为{0}次", count);
Console.ReadKey();
#endregion
#region 方法4:用Contains
string strContent = "今天天气好晴朗处处好风光,今天天气好,今天天气好今天好天气,今天天天好天气";
//字符串替换
strContent = strContent.Replace("今天", "@");
int count = 0;
for (int i = 0; i < strContent.Length; i++)
{
if (strContent[i].Equals('@'))
{
count++;
}
}
Console.WriteLine("\"今天\"出现的次数为{0}次", count);
Console.ReadKey();
#endregion
}
}