2013-01-11 326 views
8

我有一個字符串(例如:"Hello there. My name is John. I work very hard. Hello there!"),我試圖找到字符串"hello there"的出現次數。到目前爲止,這是我的代碼有:如何找到字符串中子字符串的出現次數vb.net

Dim input as String = "Hello there. My name is John. I work very hard. Hello there!" 
Dim phrase as String = "hello there" 
Dim Occurrences As Integer = 0 

If input.toLower.Contains(phrase) = True Then 
    Occurrences = input.Split(phrase).Length  
    'REM: Do stuff 
End If 

不幸的是,這行代碼,似乎做的每一次拆分字符串它看到的phrase的第一個字母,在這種情況下,h。所以,而不是我希望的結果Occurrences = 2,我實際上得到一個更大的數字。我知道計算一個字符串中分割的次數是一個可怕的方式去做這件事,即使我確實得到了正確的答案,所以有人可以幫助我並提供一些幫助嗎?

+0

問題不是很好形成。如果您使用vb.net進行標記,則Split函數將接受一個字符串,而不僅僅是一個字符。因此,在你的情況下它會是3,因爲你忘了減1。參考:https://msdn.microsoft.com/en-us/library/system.string.split%28v=vs.110%29.aspx – Gaucho

回答

2

您可以創建一個Do Until循環,停止一旦一個整數變量等於你正在檢查的字符串的長度。如果該短語存在,則增加您的出現次數,並將短語的長度加上發現它的位置添加到遊標變量中。如果無法找到該短語,則完成搜索(不再有結果),因此將其設置爲目標字符串的長度。要不止一次計算相同的出現次數,只需從光標檢查循環(strCheckThisString)中目標字符串的長度。

Dim input As String = "hello there. this is a test. hello there hello there!" 
    Dim phrase As String = "hello there" 
    Dim Occurrences As Integer = 0 

    Dim intCursor As Integer = 0 
    Do Until intCursor >= input.Length 

     Dim strCheckThisString As String = Mid(LCase(input), intCursor + 1, (Len(input) - intCursor)) 

     Dim intPlaceOfPhrase As Integer = InStr(strCheckThisString, phrase) 
     If intPlaceOfPhrase > 0 Then 

      Occurrences += 1 
      intCursor += (intPlaceOfPhrase + Len(phrase) - 1) 

     Else 

      intCursor = input.Length 

     End If 

    Loop 
+0

這看起來不錯,但是你可以添加一些關於你在做什麼的解釋嗎? – Matt

+0

謝謝。用描述編輯。 – N0Alias

+0

不知道爲什麼這是'最佳答案' - 下面的Neolisk的字符串替換方法更清晰... 試試吧! Print Len(「Cat/Dogo/Rabbit」) - Len(Replace(「Cat/dog/Rabbit」,「/」,「」)) - 1 – jcansell

2

您只需將分割函數的輸入更改爲一個字符串數組,然後拖動StringSplitOptions即可。

試試這行代碼:

Occurrences = input.Split({phrase}, StringSplitOptions.None).Length 

我沒有檢查這一點,但我想你也必須考慮到一個事實,即出現會太高由於您正在使用您的字符串分割,而不是實際計算它是字符串中有多少次,所以我覺得Occurrences = Occurrences - 1

希望這有助於

10

另一個想法:

Dim input As String = "Hello there. My name is John. I work very hard. Hello there!" 
Dim phrase As String = "Hello there" 
Dim Occurrences As Integer = (input.Length - input.Replace(phrase, String.Empty).Length)/phrase.Length 

你只需要確保phrase.Length > 0

0

我不知道這是否更明顯? 從longString開始檢查phrase中的數字字符的下一個字符,如果沒有找到phrase從第二個字符開始查找等。如果發現從當前位置開始agin加上phrase中的字符數和遞增值occurences

Module Module1 
Sub Main() 

    Dim longString As String = "Hello there. My name is John. I work very hard. Hello there! Hello therehello there" 

    Dim phrase As String = "hello There" 


    Dim occurences As Integer = 0 
    Dim n As Integer = 0 

    Do Until n >= longString.Length - (phrase.Length - 1) 
     If longString.ToLower.Substring(n, phrase.Length).Contains(phrase.ToLower) Then 
      occurences += 1 
      n = n + (phrase.Length - 1) 
     End If 
     n += 1 
    Loop 
    Console.WriteLine(occurences) 


End Sub 
End Module 
2

您可以使用IndexOf創建一個遞歸函數。傳遞要搜索的字符串和要查找的字符串,每個遞歸會增加一個計數器,並將StartIndex設置爲最後找到的索引+1,直到找不到搜索字符串。功能需要的可選參數起始位置,計數器按引用傳遞:

Function InStrCount(ByVal SourceString As String, _ 
        ByVal SearchString As String, _ 
        Optional ByRef StartPos As Integer = 0, _ 
        Optional ByRef Count As Integer = 0) As Integer 
    If SourceString.IndexOf(SearchString, StartPos) > -1 Then 
     Count += 1 
     InStrCount(SourceString, _ 
        SearchString, _ 
        SourceString.IndexOf(SearchString, StartPos) + 1, _ 
        Count) 
    End If 
    Return Count 
End Function 

呼叫傳入字符串搜索和字符串來定位和可選功能,開始位置:

Dim input As String = "Hello there. My name is John. I work very hard. Hello there!" 
Dim phrase As String = "hello there" 
Dim Occurrences As Integer 

Occurrances = InStrCount(input.ToLower, phrase.ToLower) 

注意使用。 ToLower,用於在比較中忽略大小寫。如果您希望比較是特定案例,請不要包含此指令。

12

做到這一點的最好辦法是這樣的:

Public Function countString(ByVal inputString As String, ByVal stringToBeSearchedInsideTheInputString as String) As Integer 
    Return System.Text.RegularExpressions.Regex.Split(inputString, stringToBeSearchedInsideTheInputString).Length -1 

End Function 
+1

這個句柄如何重疊搜索字符串? 'Dim inputString =「歌曲ABBABBA popsongs」'和'Dim stringToBeSearchedInsideTheInputString =「ABBA」'返回的值是什麼(1或2)? – roland

+0

有趣的觀察。在我的解決方案中,ABBA的發現是1。如果你需要處理這種異常,你需要不同的方法,但我從不需要它。注意:即使接受的解決方案也不符合您的需求。 – Gaucho

1

看你原來的嘗試,我發現,這應該做的伎倆是「拆分」創建一個數組。 紀錄= input.split(短語).ubound

這是大小寫敏感的,所以你的情況應了那句輸入

0

我用等於「你好」,因爲沒有「你好」這在VBScript中,您可以在同一轉換成VB.net以及

Dim str, strToFind 
str = "sdfsdf:sdsdgs::" 
strToFind = ":" 

MsgBox GetNoOfOccurranceOf(strToFind, str) 

Function GetNoOfOccurranceOf(ByVal subStringToFind As String, ByVal strReference As String) 
    Dim iTotalLength, newString, iTotalOccCount 
    iTotalLength = Len(strReference) 
    newString = Replace(strReference, subStringToFind, "") 
    iTotalOccCount = iTotalLength - Len(newString) 
    GetNoOfOccurranceOf = iTotalOccCount 
End Function 
0

我知道這個線程是真的老了,但我得到了另一種解決方案也:

Function countOccurencesOf(needle As String, s As String) 
    Dim count As Integer = 0 
    For i As Integer = 0 to s.Length - 1 
     If s.Substring(i).Startswith(needle) Then 
      count = count + 1 
     End If 
    Next 
    Return count 
End Function 
2
str="Thisissumlivinginsumgjhvgsum in the sum bcoz sum ot ih sum" 
b= LCase(str) 
array1=Split(b,"sum") 
l=Ubound(array1) 
msgbox l 

輸出給你的號碼。在另一個字符串中出現的字符串。基於InStr(i, str, substr)功能

1

還有一種溶液(搜索在strsubstri位置,more info about InStr()開始):

Function findOccurancesCount(baseString, subString) 
    occurancesCount = 0 
    i = 1 
    Do 
     foundPosition = InStr(i, baseString, subString) 'searching from i position 
     If foundPosition > 0 Then      'substring is found at foundPosition index 
      occurancesCount = occurancesCount + 1  'count this occurance 
      i = foundPosition + 1      'searching from i+1 on the next cycle 
     End If 
    Loop While foundPosition <> 0 
    findOccurancesCount = occurancesCount 
End Function 

一旦沒有找到字符串(InStr返回0,代替在找到的子串位置基本字符串),搜索結束並返回發生次數。

相關問題