2013-05-08 292 views
0

我有以下函數似乎工作。這是在設計代碼:在字符串中查找字符串的第一個實例

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內的參數的位置。
這是一個有效的方法嗎?
它容易破裂嗎?
有更好的解決方案嗎?

+5

[''String.IndexOf'](http://msdn.microsoft.com/en-us/library/system.string.indexof.aspx)? – 2013-05-08 07:27:59

+1

如果你必須重新實現它,在另一個方向運行循環(從0到'startingPoint',你可能要重新命名),並改變'foundPosition = iPosition'到'返回iPosition' – 2013-05-08 07:31:30

+0

@Damien_The_Unbeliever你的第二個評論是我之後的信息片斷....有一種感覺,我錯過了一些明顯的東西。 – whytheq 2013-05-08 11:46:19

回答

2

這是一個有效的方法嗎?

是的,它是一個有效的approuch,但它不是完成任務的可行途徑。順便說一下這種approuch肯定會改善你的logical skills

有沒有更好的辦法呢?

建在function調用IndexOf可用於簡單地實現您的任務。如果可用,它將返回string中特定文本的index。否則它會簡單的返回-1

附加信息:

即使你開始搜索字符串用FText結束的話,你的代碼將返回這樣做,它的第一occurance.Instead的指數你可以從一開始就像我給出的代碼一樣開始你的循環。順便說一下,您應該使用Exit For/Return來打破for循環中匹配if語句結尾處的for循環。

For iPosition As Integer = 0 To len(Text) 
     If fText.Substring(iPosition, wordLen) = word Then 
      Return iPosition 
     End If 
Next iPosition 
Return -1 
+0

...我的方法叫做FindFirst,因爲我想查找_first_實例。你的腳本可以工作,但我需要去掉'Step-1',然後我相信Damien在OP註釋部分的建議比使用Exit For更加優雅。也許你可以編輯你的文章,以便它成爲答案? – whytheq 2013-05-08 11:48:41

+0

@whytheq哦,我只是覺得你正在尋找該字符串的最後一個索引。現在我只是根據您的要求修改代碼和解釋。 – 2013-05-08 12:17:23

+0

謝謝Raju:我已經測試過,並且似乎在'For'中只有一個-1就可以正常工作。再次感謝您的努力。 – whytheq 2013-05-09 06:35:29

3

你可能只想使用內置的字符串的方法IndexOf

+0

+1感謝 - 更多的信息re.'通常有一種更快的方式 – whytheq 2013-05-08 11:46:50

1

有一個已經實現的功能做在.NET中,試試這個:

​​

如果你想最後的外觀:

index = fText.LastIndexOf(word) 
+0

+1 LastIndexOf' – whytheq 2013-05-08 11:47:29

相關問題