如何查找字符串vb.net中子字符串的出现次数

时间:2013-01-11 20:57:52

标签: vb.net string split substring

我有一个字符串(例如:"Hello there. My name is John. I work very hard. Hello there!"),我试图找到字符串"hello there"的出现次数。到目前为止,这是我的代码:

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。我知道计算一个字符串中的分裂数是一种可怕的方法,即使我得到了正确的答案,所以有人可以帮助我并提供一些帮助吗?

12 个答案:

答案 0 :(得分:14)

最好的方法是:

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 :(得分:13)

又一个想法:

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

答案 2 :(得分:4)

str="Thisissumlivinginsumgjhvgsum in the sum bcoz sum ot ih sum"
b= LCase(str)
array1=Split(b,"sum")
l=Ubound(array1)
msgbox l

输出给你的号码。另一个字符串中出现的字符串。

答案 3 :(得分:3)

您可以创建一个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

答案 4 :(得分:2)

您只需将split函数的输入更改为字符串数组,然后对StringSplitOptions进行更改。

试用这行代码:

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

我没有检查过这个,但是我想你也必须考虑到这样一个事实:由于你使用你的字符串进行拆分并且没有实际计算多少次,事件会过高它在字符串中,所以我认为 Occurrences = Occurrences - 1

希望这有帮助

答案 5 :(得分:2)

您可以使用IndexOf创建递归函数。传递要搜索的字符串和要定位的字符串,每次递归都会递增计数器并将StartIndex设置为最后找到的索引+1,直到找不到搜索字符串。函数将需要可选参数Starting Position和Counter通过引用传递:

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,用于忽略比较中的大小写。如果您希望比较是特定于案例,请不要包含此指令。

答案 6 :(得分:2)

基于InStr(i, str, substr)函数的另一个解决方案(从substr位置more info about InStr()开始,在str中搜索i):

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,而不是在基本字符串中找到子字符串位置),搜索结束并返回出现计数。

答案 7 :(得分:1)

看看你原来的尝试,我发现这应该可以解决问题,因为“Split”会创建一个数组。 出现次数= input.split(短语).ubound

这是CaSe敏感的,所以在你的情况下,短语应该等于“Hello there”,因为输入中没有“你好”,

答案 8 :(得分:1)

扩展Sumit Kumar's simple solution(请赞成his answer而不是这个),这里它是单行工作功能:

Public Function fnStrCnt(ByVal str As String, ByVal substr As String) As Integer
    fnStrCnt = UBound(Split(LCase(str), substr))
End Function

演示:

Sub testit()
    Dim thePhrase
    thePhrase = "Once upon a midnight dreary while a man was in a house in the usa."
    If fnStrCnt(thePhrase, " a ") > 1 Then
        MsgBox "Found " & fnStrCnt(thePhrase, " a ") & " occurrences."
    End If
End Sub 'testit()

答案 9 :(得分:0)

我不知道这是否更明显? 从longString开始,检查下一个字符到phrase中的数字字符,如果找不到phrase,请从第二个字符开始查找等。如果找到,请从当前位置加上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

答案 10 :(得分: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

答案 11 :(得分: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