string 如何查找字符串中子字符串的出现次数 vb.net
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14286505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to find the number of occurrences of a substring within a string vb.net
提问by Matt
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:
我有一个字符串(例如:)"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
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?
不幸的是,这行代码似乎是在每次看到 的第一个字母时拆分字符串phrase
,在本例中为h
。因此Occurrences = 2
,我实际上得到了一个更大的数字,而不是我所希望的结果。我知道计算字符串中的分割数是一种可怕的方法,即使我确实得到了正确的答案,所以有人可以帮助我并提供一些帮助吗?
采纳答案by N0Alias
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).
您可以创建一个 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
回答by Neolisk
Yet another idea:
还有一个想法:
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
You just need to make sure that phrase.Length > 0
.
您只需要确保phrase.Length > 0
.
回答by Gaucho
the best way to do it is this:
最好的方法是这样的:
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
回答by Sumit Kumar
str="Thisissumlivinginsumgjhvgsum in the sum bcoz sum ot ih sum"
b= LCase(str)
array1=Split(b,"sum")
l=Ubound(array1)
msgbox l
the output gives u the no. of occurences of a string within another one.
输出给了你编号。一个字符串在另一个字符串中出现的次数。
回答by Ivan Gerasimenko
One more solution based on InStr(i, str, substr)
function (searching substr
in str
starting from i
position, more info about InStr()):
另一种基于InStr(i, str, substr)
函数的解决方案(从位置开始搜索substr
,有关 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
As soon as there is no substring found (InStr
returns 0
, instead of found substring position in base string), searching is over and occurances count is returned.
一旦没有找到子字符串(InStr
返回0
,而不是在基字符串中找到的子字符串位置),搜索结束并返回出现次数。
回答by Jon Wilmer
You could create a recursive function using IndexOf. Passing the string to be searched and the string to locate, each recursion increments a Counter and sets the StartIndex to +1 the last found index, until the search string is no longer found. Function will require optional parameters Starting Position and Counter passed by reference:
您可以使用 IndexOf 创建递归函数。传递要搜索的字符串和要定位的字符串,每次递归都会增加一个 Counter 并将 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
Call function by passing string to search and string to locate and, optionally, start position:
通过将字符串传递给搜索和字符串来定位和(可选)开始位置来调用函数:
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)
Note the use of .ToLower, which is used to ignore case in your comparison. Do not include this directive if you do wish comparison to be case specific.
请注意 .ToLower 的使用,它用于在比较中忽略大小写。如果您确实希望比较特定于案例,请不要包含此指令。
回答by John Bustos
You just have to change the input of the split function into a string array and then delare the StringSplitOptions
.
您只需要将 split 函数的输入更改为字符串数组,然后将StringSplitOptions
.
Try out this line of code:
试试这行代码:
Occurrences = input.Split({phrase}, StringSplitOptions.None).Length
I haven't checked this, but I'm thinking you'll also have to account for the fact that occurrences would be too high due to the fact that you're splitting using your string and not actually counting how many times it is in the string, so I thinkOccurrences = Occurrences - 1
我没有检查过这个,但我认为你还必须考虑这样一个事实,即出现次数会太高,因为你使用字符串拆分而不实际计算它出现的次数字符串,所以我认为Occurrences = Occurrences - 1
Hope this helps
希望这可以帮助
回答by NeilR
Looking at your original attempt, I have found that this should do the trick as "Split" creates an array. Occurrences = input.split(phrase).ubound
查看您最初的尝试,我发现这应该可以解决问题,因为“拆分”会创建一个数组。出现次数 = input.split(phrase).ubound
This is CaSe sensitive, so in your case the phrase should equal "Hello there", as there is no "hello there" in the input
这是 CaSe 敏感的,因此在您的情况下,该短语应等于“Hello there”,因为输入中没有“hello there”
回答by cssyphus
Expanding on Sumit Kumar's simple solution(please upvote his answerrather than this one), here it is as a one-line working function:
扩展Sumit Kumar 的简单解决方案(请赞成他的答案而不是这个答案),这里是一个单行工作功能:
Public Function fnStrCnt(ByVal str As String, ByVal substr As String) As Integer
fnStrCnt = UBound(Split(LCase(str), substr))
End Function
Demo:
演示:
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()
回答by Maddy
I used this in Vbscript, You can convert the same to VB.net as well
我在 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