欢迎投稿

今日深度:

C#学习05——IndexOf,

C#学习05——IndexOf,


IndexOf()的使用

例子:查找指定的字符串

string str = "lloolloolol";
int index = 0;	//索引
int count = 0;	//次数
string keyword = "ol";	//指定字符串
if (index < str.Length) {	//查找的位置不能大于字符串长度
	while ((index = str.IndexOf(keyword, index)) != -1) {
		count++;
		Console.WriteLine("出现了{0}次,索引是{1}", count, index);
		index += keyword.Length;//从找到的索引的下一个位置开始找
	}
} else {
	Console.WriteLine("未找到指定字符串");
}
Console.ReadKey();

任意定义一个字符串变量str,在str中查找一段指定字符串“ol”,如果找到,则输出出现的次数count以及出现的位置index,若没有找到则输出“未找到指定字符串”。

str.IndexOf(keyword, index),IndexOf()函数将返回一个索引位置,若没有找到则返回-1。
索引位置!= -1说明找到了指定字符串,count +1,并将索引值赋值给index。输出“出现了count次,索引是index”。
本例子第一次执行后index = 3,count = 1。输出结果后,下一次查找的索引值index = index(本次找到的位置) + keyword.Length(指定字符串长度),这样可以直接跳过已找到的指定字符串,从下一个位置开始查找。
最后输出结果如下图:

版权声明:本文为博主原创文章,未经博主允许不得转载。

www.htsjk.Com true http://www.htsjk.com/shujukunews/10047.html NewsArticle C#学习05——IndexOf, IndexOf()的使用 例子:查找指定的字符串 string str = "lloolloolol";int index = 0;//索引int count = 0;//次数string keyword = "ol";//指定字符串if (index str.Length) {//查找的位置不能大于...
评论暂时关闭