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 )
新聞熱點
疑難解答