Mat*_*att 10 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
Run Code Online (Sandbox Code Playgroud)
不幸的是,这行代码似乎是在每次看到第一个字母时分割字符串phrase,在本例中h.因此Occurrences = 2,我实际上得到的数字要大得多,而不是我希望得到的结果.我知道计算一个字符串中的分裂数是一种可怕的方式,即使我得到了正确的答案,所以有人可以帮助我并提供一些帮助吗?
Neo*_*isk 16
另一个想法:
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
Run Code Online (Sandbox Code Playgroud)
你只需要确保这一点phrase.Length > 0.
Gau*_*cho 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
Run Code Online (Sandbox Code Playgroud)
小智 5
str="Thisissumlivinginsumgjhvgsum in the sum bcoz sum ot ih sum"
b= LCase(str)
array1=Split(b,"sum")
l=Ubound(array1)
msgbox l
Run Code Online (Sandbox Code Playgroud)
输出给了你编号。一个字符串在另一个字符串中出现的次数。
您可以创建一个 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
60917 次 |
| 最近记录: |