首页 > 编程 > C# > 正文

C#中指定搜索起始位置和搜索字符数的字符搜索函数IndexOf

2023-05-03 13:32:42
字体:
来源:转载
供稿:网友

我们在搜索一个字符串中是否包含一个指定的字符时,可以指定被搜索字符串中的起始位置,所涉及的函数原型如下:

public int IndexOf( char value, int startIndex, int count )

这个方法有三个参数,第一个参数指定要搜索的字符值,第二个参数指定搜索的起始位置,count指定搜索的字符数。

其返回值有两种情况,如果搜索到了指定的字符,则返回该字符从0开始的位置值,否则返回-1。

下面是一个例子:

string str = "武林网VEVB欢迎您。";
int iPos1 = str.IndexOf('I', 2, 1);
int iPos2 = str.IndexOf('I', 5, 3);
int iPos3 = str.IndexOf('I',1, 2);
int iPos4 = str.IndexOf('I',1, 3);
int iPos5 = str.IndexOf('I', 5, 7);

上面的例子中,iPos1=-1,iPos2 = -1,iPos3 = -1, iPos4 = 3,而int iPos5这一行将引发异常,原因是给定的第三个参数值7,超出了字符串的索引(从索引5往后数7个位置,不存在)。

IndexOf方法还有其它八种重载形式:

(1)public int IndexOf(char value)

(2)public int IndexOf(char value, int startIndex)

(3)public int IndexOf( string value, int startIndex)

(4)public int IndexOf(string value,StringComparison comparisonType )

(5)public int IndexOf(string value )

(6)public int IndexOf(string value,int startIndex,int count )

(7)public int IndexOf(string value,int startIndex,StringComparison comparisonType )

(8)public int IndexOf(string value,int startIndex,int count, StringComparison comparisonType )

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表