Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Occurs in C#
Message
 
 
To
27/02/2013 09:44:13
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:
01567039
Views:
25
>>>>>I have updated my answer
>>>>
>>>>I have a compiler warning (green underline) under this test
>>>>
>>>>
>>>> public static Int32 Occurs(this String source, char pattern)
>>>>      {
>>>>         if (null==pattern)
>>>>            return 0;
>>>>         return source.Split(pattern).Length - 1;
>>>>      }
>>>>
>>>>It is saying that value of type int never equals null.
>>>>
>>>>So, do I really need this test here for char?
>>>
>>>
>>>No - I only mentioned for pattern = string
>>
>>I guess I misunderstood you. I removed that test from the first method and onle kept in the second with String.IsNullOrEmpty check.
>>
>>Thanks again.
>
>But I would use a loop - as Viv mentioned
>
>
>
>		public static int Occurs(this String source, char c)
>		{
>			int count = 0;
>			for (int i = source.Length; --i >= 0; )
>				if (source[i] == c)
>					count++;
>
>			return count;
>		}
>
I think what I have is OK and it's a short code.
/// <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)
      {
         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
Next
Reply
Map
View

Click here to load this message in the networking platform