首页 > 编程 > C# > 正文

C#中指定起始位置、搜索字符数和搜索类型的IndexOf方法

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

C#中的IndexOf方法用于搜索指定的字符串在当前 String 对象中的第一个匹配项的索引。 这个方法有多种重载形式,本文主要讲解指定搜索起始位置、搜索字符数量和搜索类型的IndexOf方法,方法原型如下:

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

这个IndexOf方法有四个参数:

第一个参数value用来指定要搜索的子字符串;第二个参数startIndex用来指定当前字符串中的起始搜索位置;第三个参数count用来指定要搜索的当前字符串中的字符数量;第四个参数comparisonType用来指定字符串的搜索类型。

第四个参数为StringComparison枚举类型,关于这个枚举类型的具体介绍,请参见StringComparison 枚举类型简介。

该方法返回整数类型,如果按照规则找到了被搜索的字符串,则返回该字符串从0计起的索引值,否则返回-1。

下面使用一个例子来说明:

string str = "武林网VEVB提供最精彩的IT技术文章。";
int iPos1 = str.IndexOf("IT", 3, 4, StringComparison.CurrentCulture);
int iPos2 = str.IndexOf("IT", 6, 5, StringComparison.CurrentCulture);
int iPos3 = str.IndexOf("IT", 10, 3, StringComparison.CurrentCulture);
int iPos4 = str.IndexOf("IT", 10, 6, StringComparison.CurrentCulture);

以上程序中,iPos1的值为3;iPos2的值为-1;iPos3的值为-1;iPos4的值为13。

IndexOf方法的其它8种重载形式如下: 

(1)public int IndexOf(char value)

(2)public int IndexOf(string value)

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

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

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

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

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