溫馨提示×

C# String.IndexOf()方法實例講解

c#
小億
135
2023-12-18 15:12:00
欄目: 編程語言

IndexOf() 方法是 C# 字符串類的一個方法,用于返回指定字符或字符串在當前字符串中第一次出現(xiàn)的位置。它的語法如下:

public int IndexOf(string value)

其中,value 參數(shù)是要查找的字符或字符串。該方法返回一個整數(shù)值,表示指定字符或字符串第一次出現(xiàn)的索引位置。如果未找到指定字符或字符串,則返回 -1。

下面是一個使用 IndexOf() 方法的示例:

string str = “Hello, World!”; int index = str.IndexOf(“World”); Console.WriteLine(index);

這段代碼會在字符串 “Hello, World!” 中查找字符串 “World”,并返回它第一次出現(xiàn)的索引位置。在這個例子中,輸出結果為 7,因為 “World” 在字符串中的索引位置是從 7 開始的。

另外,IndexOf() 方法還可以接受一個可選的參數(shù) startIndex,用于指定從哪個索引位置開始查找。例如:

string str = “Hello, World!”; int index = str.IndexOf(“o”, 5); Console.WriteLine(index);

在這個示例中,我們指定從索引位置為 5 的字符開始查找字符 “o”,輸出結果為 7,因為第一個 “o” 出現(xiàn)在索引位置 7。

需要注意的是,IndexOf() 方法區(qū)分大小寫。如果要進行大小寫不敏感的查找,可以使用 IndexOf() 方法的重載形式:

public int IndexOf(string value, StringComparison comparisonType)

其中,comparisonType 參數(shù)是一個 StringComparison 枚舉值,用于指定查找時是否忽略大小寫。例如:

string str = “Hello, World!”; int index = str.IndexOf(“world”, StringComparison.OrdinalIgnoreCase); Console.WriteLine(index);

在這個示例中,使用 OrdinalIgnoreCase 參數(shù)進行大小寫不敏感的查找,輸出結果為 7。

0