Reputation: 7411
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
Upvotes: 73
Views: 308686
Reputation: 29
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
.
Upvotes: 2
Reputation: 1
' 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
Upvotes: 0
Reputation: 2433
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
Upvotes: 73
Reputation: 405
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.
Upvotes: 9
Reputation: 11
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.
Upvotes: 1
Reputation: 1
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.
Upvotes: 0
Reputation: 1
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
Upvotes: -3
Reputation: 2940
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');
Upvotes: 1
Reputation: 21
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")
Upvotes: 2
Reputation: 51
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())
Upvotes: 5
Reputation: 1275
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
Upvotes: -9
Reputation: 1449
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
Upvotes: 5
Reputation: 2244
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.
Upvotes: 0
Reputation: 565
Another possibility is to work with Split:
Dim tmp() As String
tmp = Split(Expression, Delimiter)
Dim count As Integer = tmp.Length - 1
Upvotes: 1
Reputation: 700152
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
Upvotes: 81
Reputation: 1158
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
Upvotes: 0
Reputation: 1908
var charCount = "string with periods...".Count(x => '.' == x);
Upvotes: 0
Reputation: 121
eCount = str.Length - Replace(str, "e", "").Length
tCount = str.Length - Replace(str, "t", "").Length
Upvotes: 1
Reputation: 19
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
Upvotes: -3
Reputation: 2241
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!
Upvotes: 22
Reputation: 39
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
Upvotes: 3
Reputation: 12465
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
Upvotes: 2
Reputation: 29
I found the best answer :P :
String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count
Upvotes: 0
Reputation: 41
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
Upvotes: 2
Reputation: 21
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
Upvotes: 2
Reputation: 361
You can try this
Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))
Upvotes: 36