Count of imbedded strings

  • Thread starter Thread starter peteZ
  • Start date Start date
P

peteZ

How do you get a count of how many times a string appears in another string
?

eg. How many times does: "abc" appear in the string: "xyxabcxyzabcxyz"

Is there a String method that does thsi - I know I have seen this before but
cannot find details on it again.

- peteZ
 
peteZ said:
How do you get a count of how many times a string appears in another string
?

eg. How many times does: "abc" appear in the string: "xyxabcxyzabcxyz"

Is there a String method that does thsi - I know I have seen this before but
cannot find details on it again.

You *could* use a regular expression, as suggested, but personally I
think that would be overkill. Here's a really simple method (with no
error detection - you might want to put parameter validation in, for
instance) which should do it:

int CountOccurrences (String haystack, String needle)
{
int start=0;
int count=0;

while (true)
{
int index = haystack.IndexOf(needle, start);
if (index==-1)
return count;
start += needle.Length;
}
}
 
How do you get a count of how many times a string appears in
another string ?

eg. How many times does: "abc" appear in the string:
"xyxabcxyzabcxyz"

Is there a String method that does thsi - I know I have seen
this before but cannot find details on it again.

You could use a regular expression:

using System.Text.RegularExpressions;
...
int count = Regex.Matches("xyxabcxyzabcxyz", "abc").Count;

Hope this helps.

Chris.
 
Back
Top