当前位置:K88软件开发文章中心编程语言.NET.NET01 → 文章内容

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

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2018-12-31 11:27:18

:2012-06-18 02:47:46

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

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

这个IndexOf方法有四个参数:

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

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

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

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

string str = "翔宇亭IT乐园提供最精彩的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)publicint IndexOf(char value)

(2)publicint IndexOf(string value)

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

(4)publicint IndexOf(string value,StringComparison comparisonType )

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

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

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

(8)publicint IndexOf(string value,int startIndex )


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