我一直在使用text.indexof()来查看字符串是否位于另一个字符串中,但是是否可以执行区分大小写/不敏感的搜索选项?我一直在寻找谷歌并没有太多运气。
如果可以计算字符串中出现的次数,那将是一个巨大的奖励!
答案 0 :(得分:6)
IndexOf
有几个带有StringComparison
参数的重载,允许您指定各种区域性和区分大小写的选项。
例如:
Dim idx As Integer = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase)
至于计数事件,没有内置任何东西,但是自己做这件事非常简单:
Dim haystack As String = "The quick brown fox jumps over the lazy dog"
Dim needle As String = "th"
Dim comparison As StringComparison = StringComparison.OrdinalIgnoreCase
Dim count As Integer = CountOccurrences(haystack, needle, comparison)
' ...
Function CountOccurrences(ByVal haystack As String, ByVal needle As String, _
ByVal comparison As StringComparison) As Integer
Dim count As Integer = 0
Dim index As Integer = haystack.IndexOf(needle, comparison)
While index >= 0
count += 1
index = haystack.IndexOf(needle, index + needle.Length, comparison)
End While
Return count
End Function