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

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

最佳答案

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

关于vb.net - 如何查找字符串中子字符串的出现次数 vb.net,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14286505/

相关文章:

java - 关于 "+"运算符及其 StringBuilder 实现

mysql - 如何在mysql中将带有方括号和逗号的字符串拆分为列和行

java - 在 Java 中用前一个字符分割字符串

asp.net-mvc - MVC 路由 - 如果 Controller 不存在,如何跳过路由规则?

vb.net - VB.NET 方法链中的换行符

c 字符数组和指针

javascript - 如何在javascript中检测字符串中的希伯来字符

asp.net - GridView 编辑按钮需要单击 2 次

vb.net - 手动添加 DataGridViewRow 导致空单元格

java - 如何根据值的动态条目拆分字符串数组?