我們?cè)谒阉饕粋€(gè)字符串中是否包含一個(gè)指定的字符時(shí),可以指定被搜索字符串中的起始位置,所涉及的函數(shù)原型如下:
public int IndexOf( char value, int startIndex, int count )
這個(gè)方法有三個(gè)參數(shù),第一個(gè)參數(shù)指定要搜索的字符值,第二個(gè)參數(shù)指定搜索的起始位置,count指定搜索的字符數(shù)。
其返回值有兩種情況,如果搜索到了指定的字符,則返回該字符從0開(kāi)始的位置值,否則返回-1。
下面是一個(gè)例子:
string str = "武林網(wǎng)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這一行將引發(fā)異常,原因是給定的第三個(gè)參數(shù)值7,超出了字符串的索引(從索引5往后數(shù)7個(gè)位置,不存在)。
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 )
新聞熱點(diǎn)
疑難解答
圖片精選