This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

13 Aug 2014

Count the occurrences of a character in a string in VB.NET

In this post, here is the VB.Net code to count the occurrences of a particular character in a given string.
Suppose there is a case  where we may want to check whether the string contains particular character or not. And we may want to count the occurrences of the character, in that case you can use this method and if count =0, then it means the character is not found.


Below are the 2 codes for the same method, you can use whatever you want.

Method 1 : 


   
    ''' <summary>
    ''' Method to count the occurrences of a charcter in a string
    ''' </summary>
    ''' <param name="inputString">InputString</param>
    ''' <param name="SearchChar">character to count</param>
    ''' <param name="matchCase">True-MatchCase, False-IgnoreCase</param>
    ''' <returns>count of given character</returns>
    ''' <remarks></remarks>
    Public Function CharCountInString(inputString As String, SearchChar As Char, matchCase As Boolean) As Integer
        Dim count As Integer = 0
        Dim chrArr As Char()
        If matchCase Then
            chrArr = inputString.ToCharArray()
        Else
            SearchChar = Char.ToLower(SearchChar)
            chrArr = inputString.ToLower().ToCharArray()
        End If

        For Each ch As Char In chrArr
            If ch = SearchChar Then
                count += 1
            End If
        Next
        Return count
    End Function



Method 2 : 

   
    ''' <summary>
    ''' Method to count the occurrences of a charcter in a string using LINQ
    ''' </summary>
    ''' <param name="inputString">InputString</param>
    ''' <param name="SearchChar">character to count</param>
    ''' <param name="matchCase">True-MatchCase, False-IgnoreCase</param>
    ''' <returns>count of given character</returns>
    ''' <remarks>.Net > 3.5 Version </remarks>
    Public Function CharCountInStringUsingLinq(inputString As String, SearchChar As Char, matchCase As Boolean) As Integer
        Dim count As Integer = 0

        If Not matchCase Then
            SearchChar = Char.ToLower(SearchChar)
            inputString = inputString.ToLower()
        End If

        count = inputString.Count(Function(x) x = SearchChar)
        ' count = inputString.Count(x => x == SearchChar) in c#
        Return count
    End Function




for C#.Net code :

>>> C#.Net code to count the occurrences of a charcter in a string