Plateforme Level Extreme
Abonnement
Profil corporatif
Produits & Services
Support
Légal
English
Occurs in C#
Message
 
 
À
26/02/2013 12:56:18
Information générale
Forum:
ASP.NET
Catégorie:
Code, syntaxe and commandes
Titre:
Versions des environnements
Environment:
C# 4.0
OS:
Windows 7
Network:
Windows 2003 Server
Database:
MS SQL Server
Divers
Thread ID:
01566946
Message ID:
01566950
Vues:
42
>>Just wondering if occurs should be implemented the same way as in SQL Server?
>
>Not the fanciest, but it does the job:
>
>
>        ' Count the occurences of one string within another
>        ' expC1 Character to look for
>        ' expC2 String
>        Public Function Occurs(ByVal tcCharacter As String, ByVal tcString As String) As Integer
>            Dim lcString As String = ""
>            Dim lnCount As Integer = 0
>            Dim lnLocation As Integer = 0
>
>            lcString = tcString
>
>            Do
>                lnLocation = lcString.IndexOf(tcCharacter, lnLocation)
>
>                If lnLocation < 0 Then
>                    Exit Do
>                Else
>                    lnCount = lnCount + 1
>                    lnLocation = lnLocation + 1
>                End If
>
>            Loop While True
>
>            Return lnCount
>        End Function
>
This is what I implemented and my test case:
String source = "Test/Here/Should/be//7/times/Here";

           Console.WriteLine("/ occurs {0} times in {1}", source.Occurs('/'), source);
           Console.WriteLine("Here occurs {0} times in {1}", source.Occurs("Here"), source);
           Console.ReadLine();
 /// <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;
      }
Is it OK?
If it's not broken, fix it until it is.


My Blog
Précédent
Suivant
Répondre
Fil
Voir

Click here to load this message in the networking platform