当前位置: 移动技术网 > IT编程>开发语言>c# > c#字符串查找某词出现的次数及索引

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

2019年07月18日  | 移动技术网IT编程  | 我要评论

字符串方法的使用:

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();

        }
    }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网