我有以下函數似乎工作。這是在設計代碼:在字符串中查找字符串的第一個實例
Method findFirst(word As String) As Integer
foundPosition As integer
Set foundPosition To -1
wordLen As integer
Set wordLen To len(word)
startingPoint As integer
Set startingPoint To (len(Text)- 1) - wordLen
For iPosition As integer From startingPoint To 0 Step -1
If substring(iPosition, wordLen) = word Then
foundPosition = iPosition
End If
Next iPosition
Return foundPosition
End Method
在VB.NET
實現我有以下幾點:
Public Function findFirst(word As String) As Integer
Dim foundPosition As Integer = -1
Dim wordLen As Integer = word.Length
Dim startingPoint As Integer = (fText.Length - 1) - wordLen
For iPosition As Integer = startingPoint To 0 Step -1
If fText.Substring(iPosition, wordLen) = word Then
foundPosition = iPosition
End If
Next iPosition
Return foundPosition
End Function
它返回現場用FText內的參數字的位置。
這是一個有效的方法嗎?
它容易破裂嗎?
有更好的解決方案嗎?
[''String.IndexOf'](http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx)? – 2013-05-08 07:27:59
如果你必須重新實現它,在另一個方向運行循環(從0到'startingPoint',你可能要重新命名),並改變'foundPosition = iPosition'到'返回iPosition' – 2013-05-08 07:31:30
@Damien_The_Unbeliever你的第二個評論是我之後的信息片斷....有一種感覺,我錯過了一些明顯的東西。 – whytheq 2013-05-08 11:46:19