2

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!

1 Answer 1

7

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 
Sign up to request clarification or add additional context in comments.

3 Comments

duh, still new to vb.net over here :) - does this apply to the text.Replace() function as well so I can do case sensitive/insensitive replaces?
@Joe: Unfortunately there aren't any equivalent overloads of Replace that take a StringComparison argument. I have a C# extension method to do this and I can paste that in if you like. (I'm not very fluent in VB myself and don't have time to translate it at the moment. Sorry.)
ah crap, no worries I'll find something else for that later on. thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.