Jason Gleason wrote:
What's the most efficient way to get the number of occurences of a certain
string in another string..for instance i'm using the following code right
now...
private int CharacterCounte r(String text,String Character)
{
int count = 0;
for (int i = 0; i < text.Length; i++)
{
if(text.Substri ng(i,1) == Character)
{
count++;
}
}
return count;
}
The problem with this way is it's not the fastest doing big strings multiple
times over the course of a program run. Is there an easier/faster way to do
it using regular expressions?
If you're searching for exact matches, regex's will not buy you anything
over a well-designed string search. if you're going to search for
patterns, regex's are a good tool.
If you want to count instances of a single character in a string (like
your example) you might be able to tune it a bit (for example, "text[i]"
is probably faster than "text.Substring (i,1)"), but your basic algorithm
is probably fine - if you're going to search the text string only once.
If you're going to count character instances in the same text string
multiple times, it would probably pay to run through the string once,
tallying up all the counts for the various characters into an array
that's indexed by the character value. Subsequent character counts are
just an indexed array access after that.
If you want to change the search from simply counting instances of a
particular character to counting actual instances of strings, you'll
probably want to do some research on the Boyer-Moore string search
algorithm. The framework's String.IndexOf( ) method might be a good
starting point for you, but I don't think it'll be as fast as a
hand-coded Boyer-Moore, since IndexOf() takes into account culture
information.
Do a net search on Boyer-Moore - it's a not-too-complex, but very, very
good algorithm for performing exact string matches.
--
mikeb