有時,我們在查找一個字符串中是否包含一個指定的子字符串時,要對搜索的大小寫等內容進行設置,這可以借助IndexOf方法的另外一種重載格式IndexOf(string value, StringComparison comparisonType)形式來進行。該方法的原型如下:
public int IndexOf( string value, StringComparison comparisonType )
該方法有兩個參數,第一個參數value是要搜索的子字符串,參數comparisonType用來指定字符串的匹配類型。
comparisonType參數是一個枚舉類型,其值有6種情況:(詳細可參見《C#中枚舉類型StringComparison簡介》)
(1)CurrentCulture 使用區域敏感排序規則和當前區域比較字符串。
(2)CurrentCultureIgnoreCase 使用區域敏感排序規則、當前區域來比較字符串,同時忽略被比較字符串的大小寫。
(3)InvariantCulture 使用區域敏感排序規則和固定區域比較字符串。
(4)InvariantCultureIgnoreCase 使用區域敏感排序規則、固定區域來比較字符串,同時忽略被比較字符串的大小寫。
(5)Ordinal 使用序號排序規則比較字符串。
(6)OrdinalIgnoreCase 使用序號排序規則并忽略被比較字符串的大小寫,對字符串進行比較。
該方法的返回值為value第一次出現的位置,如果未搜索到子字符串,則返回-1.
下面用一個例子來說明該方法的具體使用方法:
string str = "武林網VEVB is professional IT WebSite。";
int iPos = str.IndexOf( "website", StringComparison.OrdinalIgnoreCase);
這個方法忽略大小寫,則返回值為27,如果不指定比較類型的話,則返回-1。
該方法的其它重載形式如下:
(1)public int IndexOf(char value)
(2)public int IndexOf(string value)
(3)public int IndexOf( string value, int startIndex)
(4)public int IndexOf(char value, int startIndex )
(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,int count, StringComparison comparisonType )
新聞熱點
疑難解答