本文說明如何在Visual Basic中搜尋字串的範例。
範例
這個範例會呼叫 IndexOf 物件上的 String 方法,以報告第一次出現子字串的索引:
Dim SearchWithinThis As String = "ABCDEFGHIJKLMNOP"
Dim SearchForThis As String = "DEF"
Dim FirstCharacter As Integer = SearchWithinThis.IndexOf(SearchForThis)
穩固程式設計
方法 IndexOf 會傳回第一個出現子字串之第一個字元的位置。 索引是以 0 為基礎,這表示字串的第一個字元索引為 0。
如果 IndexOf 找不到子字串,則會傳回 -1。
方法 IndexOf 會區分大小寫,並使用目前的文化特性。
為了獲得最佳錯誤控制,您可能會想要將字串搜尋包在 Try
Try...Catch...Finally 語句結構中。