Windows Phone Developers

Tuesday, August 30, 2011

How to count a string within another string in VB.NET/C#

How to get number of given string using C#/VB.NET

After a lull I wanted to start somewhere; here is what I got for now (thanks to Arivuchutarji who initiated this debate).

We have come across many situations where we need to count a string within other.

There are three ways to do (infact two)

1. Linq
2. A Do While loop using IndexOf
3. Regular Expressions

Here is the LINQ one - it applies to characters and not strings (appreciate if someone could post searching a text within a string)

        Dim sCollection As String
        sCollection = "this is a string with some text repeated and some not"
        Dim count As Integer
        count = (From sText In sCollection
                         Where sText = "s"
                         Select sText).Count

The second one appears primitive - but a foolproof method

        Dim cntStr = -1, i1, iStart As Integer
        Dim searchString As String
        searchString = "some"
        Do While i1 <> -1
            i1 = sCollection.IndexOf(searchString, iStart)
            iStart = i1 + 1
        Loop

And finally, my favorite regular expressions - code is clean if you use this

        cntStr = RegularExpressions.Regex.Matches(sCollection, "some").Count

Appreciate your comments on this Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon