4

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.

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

4 Comments

id be interested to know the performance of this, but +1 for clear simple code.
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.
This will not work as expected if inputString contains special characters. You need to call Regex.Escape.
@Jonathan: If you use this, change it to Regex.Matches(textBox1.Text, Regex.Escape(inputString)).Count.
0

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.

6 Comments

I'm sorry but this is about twice as slow as regex, tested and benchmarked. Code at pastebin.com/m52d69edc
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.
I must say that that's quite surprising.
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.
Actually, a loop using instr is about 30% faster than regex in this case.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.