C#中的IndexOf方法用于搜索指定的字符串在當(dāng)前 String 對象中的第一個匹配項(xiàng)的索引。 這個方法有多種重載形式,本文主要講解指定搜索起始位置、搜索字符數(shù)量和搜索類型的IndexOf方法,方法原型如下:
public int IndexOf(string value, int startIndex,int count,StringComparison comparisonType)
這個IndexOf方法有四個參數(shù):
第一個參數(shù)value用來指定要搜索的子字符串;第二個參數(shù)startIndex用來指定當(dāng)前字符串中的起始搜索位置;第三個參數(shù)count用來指定要搜索的當(dāng)前字符串中的字符數(shù)量;第四個參數(shù)comparisonType用來指定字符串的搜索類型。
第四個參數(shù)為StringComparison枚舉類型,關(guān)于這個枚舉類型的具體介紹,請參見StringComparison 枚舉類型簡介。
該方法返回整數(shù)類型,如果按照規(guī)則找到了被搜索的字符串,則返回該字符串從0計(jì)起的索引值,否則返回-1。
下面使用一個例子來說明:
string str = "武林網(wǎng)VEVB提供最精彩的IT技術(shù)文章。";
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 )
新聞熱點(diǎn)
疑難解答
圖片精選