如何查找字符串中子字符串的出现次数 vb.net [英] how to find the number of occurrences of a substring within a string vb.net
问题描述
我有一个字符串(例如:"Hello你好"
.到目前为止,这是我拥有的代码:
I have a string (for example: "Hello there. My name is John. I work very hard. Hello there!"
) and I am trying to find the number of occurrences of the string "hello there"
. So far, this is the code I have:
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
,我实际上得到了一个更大的数字.我知道计算字符串中的分割数是一种可怕的方法,即使我确实得到了正确的答案,所以有人可以帮助我并提供一些帮助吗?
Unfortunately, what this line of code seems to do is split the string every time it sees the first letter of phrase
, in this case, h
. So instead of the result Occurrences = 2
that I would hope for, I actually get a much larger number. I know that counting the number of splits in a string is a horrible way to go about doing this, even if I did get the correct answer, so could someone please help me out and provide some assistance?
推荐答案
您可以创建一个 Do until 循环,该循环在整数变量等于您要检查的字符串的长度时停止.如果该短语存在,则增加出现次数并将该短语的长度加上找到它的位置添加到游标变量中.如果找不到该短语,则您已完成搜索(没有更多结果),因此将其设置为目标字符串的长度.为了不计算多次相同的出现,只检查从游标到循环中目标字符串的长度(strCheckThisString).
You can create a Do Until loop that stops once an integer variable equals the length of the string you're checking. If the phrase exists, increment your occurences and add the length of the phrase plus the position in which it is found to the cursor variable. If the phrase can not be found, you are done searching (no more results), so set it to the length of the target string. To not count the same occurance more than once, check only from the cursor to the length of the target string in the Loop (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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!