>>>Hi everybody,
>>>
>>>Just wondering if occurs should be implemented the same way as in SQL Server?
>>>
>>>E.g.
>>>
>>>string.Length - String.replace(stringToTest,"").Length
>>>
>>
>>
>>What's wrong with String.Contains() ? Why do you need a replace()
>>
>>
>>
>>>
>>>Thanks in advance.
>>>
>>>Found this implementation also
>>>
>>>
http://www.dotnetperls.com/string-occurrence>>>
>>>wondering if I should go with my first idea or this one.
>>>
>>>Found this discussion
>>>
>>>
http://stackoverflow.com/questions/541954/how-would-you-count-occurences-of-a-string-within-a-string-c>>>
>>>I think I may need two separate methods - one for string and one for char.
>
>Contains returns boolean. I need number of occurrences. I checked that thread in stackoverflow, looks like it doesn't matter for a single test which method to implement. Just wondering if my current implementation is OK as is:
>
Looks OK
Update
But you may want to test
(1) pattern == null
(2) pattern.Length == 0 ( division by zero)
>
> /// <summary>
> /// Occurs function
> /// </summary>
> /// <param name="source"></param>
> /// <param name="pattern"></param>
> /// <returns></returns>
> public static Int32 Occurs(this String source, char pattern)
> {
> return source.Split(pattern).Length - 1;
> }
>
> public static Int32 Occurs(this String source, String pattern)
> {
> return (source.Length - source.Replace(pattern, "").Length)/pattern.Length;
> }
Gregory