views:

412

answers:

2

How can I get how many times a string occurs in a textbox?

I thought the find function would return the number of times found but it seems to return the location of it.

+7  A: 

Regex.Matches(textBox1.Text, Regex.Escape(inputString)).Count

Aviad P.
id be interested to know the performance of this, but +1 for clear simple code.
Matt Joslin
thank you, what do I have to import to use it?
Jonathan
`Import System.Text.RegularExpressions`Regex provides best performance for simple searches, especially if you use the `Compiled` flag and precreate the regex object. But I never benchmarked this.
Aviad P.
This will not work as expected if `inputString` contains special characters. You need to call `Regex.Escape`.
SLaks
It worked, except it is count not length at the end.
Jonathan
@Jonathan: If you use this, change it to `Regex.Matches(textBox1.Text, Regex.Escape(inputString)).Count`.
SLaks
I'm sorry, fixed.
Aviad P.
A: 

You can call Split, like this:

(" " + textBox1.Text + " ").Split(New String() { inputString }, StringSplitOptions.None);

Alternatively, you can keep calling IndexOf with the startIndex equal to the previous call's return value + 1 until it returns -1.

SLaks
I'm sorry but this is about twice as slow as regex, tested and benchmarked. Code at http://pastebin.com/m52d69edc
Aviad P.
Even without precompiling the regex, and with using Regex.Escape on each call, the regex is still twice as fast as the Split way, plus you can divine additional information from the regex such as where the matches are located in the original string.
Aviad P.
I must say that that's quite surprising.
SLaks
Few things can beat the performance of a well-implemented regular expression search engine, provided the pattern and the text are not known or indexed in advance.
Aviad P.
Actually, a loop using instr is about 30% faster than regex in this case.
xpda
What if you need to search one of two words? :-)
Aviad P.