Count specific character occurrences in a string

vb.netString

vb.net Problem Overview


What is the simplest way to count the number of occurrences of a specific character in a string?

That is, I need to write a function, countTheCharacters(), so that

str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3

vb.net Solutions


Solution 1 - vb.net

The most straightforward is to simply loop through the characters in the string:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Dim cnt As Integer = 0
  For Each c As Char In value
    If c = ch Then 
      cnt += 1
    End If
  Next
  Return cnt
End Function

Usage:

count = CountCharacter(str, "e"C)

Another approach that is almost as effective and gives shorter code is to use LINQ extension methods:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return value.Count(Function(c As Char) c = ch)
End Function

Solution 2 - vb.net

This is the simple way:

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3

Solution 3 - vb.net

You can try this

Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))

Solution 4 - vb.net

Here's a simple version.

text.count(function(x) x = "a")

The above would give you the number of a's in the string. If you wanted to ignore case:

text.count(function(x) Ucase(x) = "A")

Or if you just wanted to count letters:

text.count(function(x) Char.IsLetter(x) = True)

Give it a shot!

Solution 5 - vb.net

Or (in VB.NET):

Function InstanceCount(ByVal StringToSearch As String,
                       ByVal StringToFind As String) As Long
    If Len(StringToFind) Then
        InstanceCount = UBound(Split(StringToSearch, StringToFind))
    End If
End Function

Solution 6 - vb.net

Conversion of Ujjwal Manandhar's code to VB.NET as follows...

Dim a As String = "this is test"
Dim pattern As String = "t"
Dim ex As New System.Text.RegularExpressions.Regex(pattern)
Dim m As System.Text.RegularExpressions.MatchCollection
m = ex.Matches(a)
MsgBox(m.Count.ToString())

Solution 7 - vb.net

Thanks, @guffa. The ability to do it in one line, or even within a longer statement in .NET is very handy. This VB.NET example counts the number of LineFeed characters:

Dim j As Integer = MyString.Count(Function(c As Char) c = vbLf)

j returns the number of LineFeeds in MyString.

Solution 8 - vb.net

I think this would be the easiest:

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return len(value) - len(replace(value, ch, ""))
End Function

Solution 9 - vb.net

Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32

    Dim iPos = -1
    Dim iFound = 0
    Do
        iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
        If iPos <> -1 Then
            iFound += 1
        End If<br/>
    Loop Until iPos = -1
    Return iFound
End Function

Code Usage:

Dim iCountTimes As Integer = CountOccurrences("Can I call you now?", "a")

Also you can have it as an extension:

<Extension()> _
Public Function CountOccurrences(ByVal StToSerach As String, ByVal StToLookFor As String) As Int32
    Dim iPos = -1
    Dim iFound = 0
    Do
        iPos = StToSerach.IndexOf(StToLookFor, iPos + 1)
        If iPos <> -1 Then
            iFound += 1
        End If
    Loop Until iPos = -1
    Return iFound
End Function

Code Usage:

Dim iCountTimes2 As Integer = "Can I call you now?".CountOccurrences("a")

Solution 10 - vb.net

Public Class VOWELS

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim str1, s, c As String
        Dim i, l As Integer
        str1 = TextBox1.Text
        l = Len(str1)
        c = 0
        i = 0
        Dim intloopIndex As Integer
        For intloopIndex = 1 To l
            s = Mid(str1, intloopIndex, 1)
            If (s = "A" Or s = "a" Or s = "E" Or s = "e" Or s = "I" Or s = "i" Or s = "O" Or s = "o" Or s = "U" Or s = "u") Then
                c = c + 1
            End If
        Next
        MsgBox("No of Vowels: " + c.ToString)
    End Sub
End Class

Solution 11 - vb.net

When I found this solution I was looking for something slightly different as the string I wanted to count was longer than one character, so I came up with this solution:

    Public Shared Function StrCounter(str As String, CountStr As String) As Integer
        Dim Ctr As Integer = 0
        Dim Ptr As Integer = 1
        While InStr(Ptr, str, CountStr) > 0
            Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
            Ctr += 1
        End While
        Return Ctr
    End Function

Solution 12 - vb.net

I suggest you to do it like this:

String.Replace("e", "").Count
String.Replace("t", "").Count

You can also use .Split("e").Count - 1 or .Split("t").Count - 1 respectively, but it gives wrong values if you, for instance have an e or a t at the beginning of the String.

Solution 13 - vb.net

Using Regular Expressions...

Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer
  Return (New System.Text.RegularExpressions.Regex(ch)).Matches(value).Count
End Function

Solution 14 - vb.net

Another possibility is to work with Split:

Dim tmp() As String
tmp = Split(Expression, Delimiter)
Dim count As Integer = tmp.Length - 1

Solution 15 - vb.net

I use LINQ, and the solution is very simple:

Code in C#:

count = yourString.ToCharArray().Count(c => c == 'e');

The code in a function:

public static int countTheCharacters(string str, char charToCount){
   return str.ToCharArray().Count(c => c == charToCount);
}

Call the function:

count = countTheCharacters(yourString, 'e');

Solution 16 - vb.net

eCount = str.Length - Replace(str, "e", "").Length
tCount = str.Length - Replace(str, "t", "").Length

Solution 17 - vb.net

What huge codes for something so simple:

In C#, create an extension method and use LINQ.

public static int CountOccurences(this string s, char c)
{
    return s.Count(t => t == c);
}

Usage:

int count = "toto is the best".CountOccurences('t');

Result: 4.

Solution 18 - vb.net

Another possibility is to use a regular expression:

string a = "this is test";
string pattern = "t";
System.Text.RegularExpressions.Regex ex = new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.MatchCollection m = ex.Matches(a);
MessageBox.Show(m.Count.ToString());

Please convert this into VB.NET.

Solution 19 - vb.net

I found the best answer :P :

String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count

Solution 20 - vb.net

    ' Trying to find the amount of "." in the text
    ' if txtName looks like "hi...hi" then intdots will = 3
    Dim test As String = txtName.Text
    Dim intdots As Integer = 0
    For i = 1 To test.Length
        Dim inta As Integer = 0 + 1
        Dim stra As String = test.Substring(inta)
        If stra = "." Then
            intdots = intdots + 1
        End If
    Next
    txttest.text = intdots

Solution 21 - vb.net

Use:

Function fNbrStrInStr(strin As Variant, strToCount As String)
    fNbrStrInStr = UBound(Split(strin, strToCount)) - LBound(Split(strin, strToCount))
End Function

I used strin as variant to handle very long text. The split can be zero-based or one-based for low end depending on user settings, and subtracting it ensures the correct count.

I did not include a test for strcount being longer than strin to keep code concise.

Solution 22 - vb.net

var charCount = "string with periods...".Count(x => '.' == x);

Solution 23 - vb.net

I use the following function. It is not the most memory efficient but it is very simple to understand, supports multiple compare methods, is only 4 lines, is fast, mostly works in VBA too, will find not just individual characters but any search string (I often search for VbCrLf (s)).

Only thing missing is the ability to start search from a different "Start"

    Function inStC(myInput As String, Search As String, Optional myCompareMethod As Long = CompareMethod.Text) As Long
        If InStr(1, myInput, Search, myCompareMethod) = 0 Then Return 0
        Return UBound(Split(myInput, Search,, myCompareMethod))
    End Function

One thing I like is that it is compact to use example.

str="the little red hen"
count=inStC(str,"e") 'count should equal 4
count=inStC(str,"t") 'count should equal 3

While I am here, I would like to shill my inStB function, which, instead of returning a count of a string, it will simply return a boolean if the search string is present. I need this function often and this makes my code cleaner.

Function inStB(myInput As String, Search As String, Optional Start As Long = 1, Optional myCompareMethod As Long = CompareMethod.Text) As Boolean
    If InStr(Start, myInput, Search, myCompareMethod) > 0 Then Return True
    Return False
End Function

Solution 24 - vb.net

Use:

Dim a
inputString = InputBox("Enter String", "Enter Value", "")

MyString = UCase(inputString)

MsgBox MyString

Dim stringLength

stringLength = Len(MyString)

Dim temp

output = ""

i = 1
Do
    temp = Mid(MyString, i, 1)

    MsgBox temp & i

    CharacterCount = len(MyString) - len(Replace(MyString, temp, ""))

    MyString = Replace(MyString, temp, "")

    output = output & temp & ": " & CharacterCount & vbNewline

Loop While MyString <> ""

MsgBox output

Solution 25 - vb.net

Private Sub Data_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Data.KeyPress
    If Not IsNumeric(e.KeyChar) And Not e.KeyChar = ChrW(Keys.Back) And Not e.KeyChar = "." Then
        e.Handled = True
    Else
        If e.KeyChar = "." And Data.Text.ToCharArray().Count(Function(c) c = ".") > 0 Then
            e.Handled = True
        End If
    End If
End Sub

Solution 26 - vb.net

Here is the direct code that solves the OP's problem:

        Dim str As String = "the little red hen"

        Dim total As Int32

        Dim Target As String = "e"
        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = str.IndexOf(Target, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        End If

        MessageBox.Show(CStr(total))

Now, this is a handy function to solve the OP's problem:

    Public Function CountOccurrence(ByVal YourStringToCountOccurrence As String, ByVal TargetSingleCharacterToCount As String) As Int32
        Dim total As Int32

        Dim Temp As Int32
        Dim Temp2 As Int32 = -1
Line50:
        Temp = YourStringToCountOccurrence.IndexOf(TargetSingleCharacterToCount, Temp2 + 1)
        Temp2 = Temp
        If Temp <> -1 Then

            ' Means there is a target there
            total = total + 1
            GoTo Line50
        Else
            Return total
        End If
    End Function

Example of using the function:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim str As String = "the little red hen"

    MessageBox.Show(CStr(CountOccurrence(str, "e")))
    ' It will return 4
End Sub

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUrbycozView Question on Stackoverflow
Solution 1 - vb.netGuffaView Answer on Stackoverflow
Solution 2 - vb.netCoyoleroView Answer on Stackoverflow
Solution 3 - vb.netMark HarrisView Answer on Stackoverflow
Solution 4 - vb.netMattBView Answer on Stackoverflow
Solution 5 - vb.netJerryOLView Answer on Stackoverflow
Solution 6 - vb.netNikcView Answer on Stackoverflow
Solution 7 - vb.netNeil DunlopView Answer on Stackoverflow
Solution 8 - vb.netJeremyView Answer on Stackoverflow
Solution 9 - vb.netNikos TziortziosView Answer on Stackoverflow
Solution 10 - vb.netSouvik BoseView Answer on Stackoverflow
Solution 11 - vb.netAndrew'View Answer on Stackoverflow
Solution 12 - vb.netOlex WhiteView Answer on Stackoverflow
Solution 13 - vb.netCarter MedlinView Answer on Stackoverflow
Solution 14 - vb.netSwissGuyView Answer on Stackoverflow
Solution 15 - vb.netJuan Carlos VelezView Answer on Stackoverflow
Solution 16 - vb.netGüven AcarView Answer on Stackoverflow
Solution 17 - vb.netFredView Answer on Stackoverflow
Solution 18 - vb.netUjjwal ManandharView Answer on Stackoverflow
Solution 19 - vb.netOlex WhiteView Answer on Stackoverflow
Solution 20 - vb.netUltimatedeath91View Answer on Stackoverflow
Solution 21 - vb.netToby YadonView Answer on Stackoverflow
Solution 22 - vb.netTimothy GonzalezView Answer on Stackoverflow
Solution 23 - vb.netShodanView Answer on Stackoverflow
Solution 24 - vb.netShashank ChouhanView Answer on Stackoverflow
Solution 25 - vb.netmoustafaghaddarView Answer on Stackoverflow
Solution 26 - vb.netPredatorView Answer on Stackoverflow