c#字符串查找某词出现的次数及索引


字符串方法的使用:

indexof():

有9个重载,具体的请转到F12查看详细内容;

本文使用的是第6个重载:

如果找到该字符串,则为从零开始的索引位置;如果未找到该字符串,则为 -1

有两个参数:

string value:要搜索的字符

int startIndex:搜索的起始位置

复制代码 代码如下:

class Program
    {
        static void Main(string[] args)
        {
            //统计出字符串中,下雪出现的次数,并每次出现的索引位置;
            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);
            Console.ReadKey();

        }
    }


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3