我們在搜索一個字符串中是否包含一個指定的字符串時,可以指定被搜索字符串中的起始位置和要搜索的字符數,所涉及的函數原型如下:
public int IndexOf( string value, int startIndex, int count )
這個方法有三個參數,第一個參數value指定要搜索的字符串值,第二個參數startIndex指定搜索的起始位置,第三個參數count指定搜索的字符數。
其返回值有兩種情況,如果搜索到了指定的字符串,則返回該字符串從0開始的位置值,否則返回-1。
下面是一個例子:
string str = "武林網VEVB歡迎您。";
int iPos1 = str.IndexOf("樂園", 2, 1);
int iPos2 = str.IndexOf("樂園", 5, 3);
int iPos3 = str.IndexOf("樂園", 1, 2);
int iPos4 = str.IndexOf("樂園", 1, 3);
int iPos5 = str.IndexOf("樂園", 5, 7);
上面的例子中,iPos1=-1,iPos2 = -1,iPos3 = -1, iPos4 = 3,而int iPos5這一行將引發異常,原因是給定的第三個參數值7,超出了字符串的索引(從索引5往后數7個位置,不存在)。
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(char 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 )
新聞熱點
疑難解答