Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Occurs in C#
Message
 
 
To
26/02/2013 13:21:14
General information
Forum:
ASP.NET
Category:
Coding, syntax and commands
Title:
Environment versions
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Miscellaneous
Thread ID:
01566946
Message ID:
01566960
Views:
34
>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;
>>      }
Good point, I guess I'll add these two checks in both and return 0 in these cases.
/// <summary>
      /// Occurs function
      /// </summary>
      /// <param name="source"></param>
      /// <param name="pattern"></param>
      /// <returns></returns>
      public static Int32 Occurs(this String source, char pattern)
      {
         if (null==pattern)
            return 0;
         return source.Split(pattern).Length - 1;
      }

      public static Int32 Occurs(this String source, String pattern)
      {
         if (String.IsNullOrEmpty(pattern))
            return 0;
         return (source.Length - source.Replace(pattern, "").Length)/pattern.Length;
      }
If it's not broken, fix it until it is.


My Blog
Previous
Reply
Map
View

Click here to load this message in the networking platform