Reputation: 3089
I've been using text.indexof() to see if a string is located inside another string, however is it it possible to do a case sensitive/insensitive search option? I've been looking around Google and not having much luck with it.
A huge bonus would be if it could count the number of occurrences inside the string!
Upvotes: 2
Views: 11331
Reputation: 269298
There are several overloads of IndexOf
that take a StringComparison
parameter, allowing you to specify the various culture and case-sensitivity options.
For example:
Dim idx As Integer = haystack.IndexOf(needle, StringComparison.OrdinalIgnoreCase)
As for counting occurrences, there's nothing built-in, but it's pretty straightforward to do it yourself:
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
Upvotes: 7