计算string中特定的字符出现次数

计算string中特定字符出现次数的最简单方法是什么?

即我需要写一个函数countTheCharacters(),以便

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

最直接的方法是简单地遍历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 

用法:

 count = CountCharacter(str, "e"C) 

另一种几乎同样有效并且代码较短的方法是使用LINQ扩展方法:

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

这是简单的方法

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

你可以试试这个

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

这是一个简单的版本。

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

以上将给你在string中的数字。 如果你想忽略大小写:

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

或者如果你只是想数字:

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

试一试!

或(在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 

将Ujjwal Manandhar的代码转换为VB.NET,如下所示…

 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()) 

谢谢, @guffa 。 在一行中,甚至在.NET中的更长的语句中执行它的function非常方便。 这个VB.NET例子计算了LineFeed字符的数量:

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

j返回MyString中的LineFeeds的数量。

 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 

当我find这个解决scheme时,我正在寻找稍微不同的东西,因为我想要计算的string长于一个字符,所以我提出了这个解决scheme:

  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 

我认为这将是最简单的:

 Public Function CountCharacter(ByVal value As String, ByVal ch As Char) As Integer Return len(value) - len(replace(value, ch, "")) End Function 
 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 

代码用法:

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

你也可以把它作为一个扩展:

 <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 

代码用法:

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

我build议你这样做:

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

你也可以使用.Split("e").Count - 1或者.Split("t").Count - 1 respetivelly,但是如果你有一个e或者at开头的String

使用正则expression式…

 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 
 eCount = str.Length - Replace(str, "e", "").Length tCount = str.Length - Replace(str, "t", "").Length 

另一种可能性是与斯普利特合作:

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

我find了最好的答案:P:

 String.ToString.Count - String.ToString.Replace("e", "").Count String.ToString.Count - String.ToString.Replace("t", "").Count 
  '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 

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

我使用以下function。 它不是最有效率的内存,但它很容易理解,支持多种比较方法,只有4行,速度快,大部分也在VBA中工作,不仅可以find单个字符而且可以查找任何string(我经常searchVbCrLf (一个或多个))。

唯一缺less的是从不同的“开始”开始search的能力

  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 

我喜欢的一件事是使用示例是紧凑的。

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

虽然我在这里,我想shill我的inStB函数,而不是返回一个string的计数,它只会返回一个布尔值,如果searchstring存在。 我经常需要这个函数,这使得我的代码更清晰。

 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 

另一种可能性是使用正则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()); 

请把它转换成VB.NET。

我使用LINQ,解决scheme非常简单:

在C#中的代码:

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

函数中的代码:

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

调用函数:

 count = countTheCharacters(yourString, 'e'); 

使用:

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

我使用strin作为变体的字符来处理非常长的文本。 拆分可以根据用户设置从零开始或基于一开始,并且减去它可以确保正确的计数。

我没有包含一个testingstrcount比strin更长的代码简洁。

什么巨大的代码如此简单:

在C#中,创build一个扩展方法并使用LINQ。

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

用法:

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

结果:4。

使用:

 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 
 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 

这是解决OP问题的直接代码:

  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)) 

现在,解决OP的问题是一个方便的function:

  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 

使用该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