操作說明:在字串內搜尋 (Visual Basic)

本文示範如何使用 Visual Basic 在字串內搜尋。

範例

此範例會在 String 物件上呼叫 IndexOf 方法,以報告第一次出現子字串的索引:

Dim SearchWithinThis As String = "ABCDEFGHIJKLMNOP"
Dim SearchForThis As String = "DEF"
Dim FirstCharacter As Integer = SearchWithinThis.IndexOf(SearchForThis)

穩固程式設計

IndexOf 方法會傳回第一次出現子字串的第一個字元位置。 此索引是以 0 起始,這表示字串中第一個字元的索引為 0。

如果 IndexOf 找不到子字串,則會傳回 -1。

IndexOf 方法會區分大小寫,並使用目前的文化特性 (Culture)。

若要獲得最佳錯誤控制,建議您以 Try...Catch...Finally Statement 建構的 Try 區塊括住字串搜尋。

另請參閱