IndexOf的用法(查找一个字符出现的次数以及索引)

 1 string msg = "大刀对单刀,单刀对大刀,大刀斗单刀,单刀夺大刀。";
 2             //判断这个字符串中大刀出现的次数,和每次出现的索引位置
 3             int count = 0;
 4             string keywords = "大刀";
 5             int index = 0;
 6             while ((index = msg.IndexOf(keywords, index)) != -1) {
 7                 count++;
 8                 Console.WriteLine("第{0}次出现【{1}】,索引是:{2}", count, keywords, index);
 9                 //下次从这个词末的位置开始查找,所以要跳过本次该词的长度个字符位置继续查找
10                 index = index + keywords.Length;
11             }
12             Console.WriteLine("==========================================");
13             Console.WriteLine("【{0}】一次一共出现了{1}次。", keywords, count);
14             Console.ReadLine();

运行结果:

************Code虽易,Debug不易,且码且珍惜************


本博客仅用于学习记录之用,如有侵权,请Email:tianqy@live.com

原文地址:https://www.cnblogs.com/tianqy/p/3982687.html