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

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

也就是说,我需要编写一个函数 count TheProperties () ,以便

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

最简单的方法是简单地循环遍历字符串中的字符:

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

另一种可能性是与 Split 合作:

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

另一种可能性是使用正则表达式:

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。

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

下面是解决 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 的问题:

    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

使用该函数的示例:

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

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

你可以试试这个

Dim occurCount As Integer = Len(testStr) - Len(testStr.Replace(testCharStr, ""))
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")

这是最简单的方法:

text = "the little red hen"
count = text.Split("e").Length -1 ' Equals 4
count = text.Split("t").Length -1 ' Equals 3
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

当我发现这个解决方案时,我正在寻找一些稍微不同的东西,因为我想要计数的字符串比一个字符长,所以我想出了这个解决方案:

    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

我建议你这样做:

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

也可以分别使用 .Split("e").Count - 1.Split("t").Count - 1,但是如果在 String的开头有一个 e 或 t,它就会给出错误的值。

我找到了最好的答案:

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

使用正则表达式..。

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

我使用 LINQ,解决方案很简单:

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

用途:

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

我想这是最简单的:

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

这里有个简单的版本。

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

如果你想忽略大小写:

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

或者如果你只是想数字:

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

试试看!

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

用途:

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

我使用 strin作为变体来处理非常长的文本。根据用户设置,分割可以从零开始,也可以从一开始,用于低端,减去它可以确保正确的计数。

为了保持代码简洁,我没有包含 strcount 长于 strin的测试。

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

这么简单的东西有多么庞大的代码:

在 C # 中,创建一个扩展方法并使用 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。

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

谢谢 @ guffa。中的一行中执行此操作,甚至在更长的语句中执行此操作的能力。NET 非常方便。这个 VB.NET 示例计算了 LineFeed 的字符数:

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

J 返回 MyString 中的 LineFeeds 数。

我使用以下函数。它不是最有效的内存,但它是非常简单的理解,支持多种比较方法,只有4行,是快速的,大部分工作在 VBA 也,会找到不只是个别字符,但任何搜索字符串(我经常搜索 VbCrLf (s))。

唯一缺少的是从不同的“开始”开始搜索的能力

    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

虽然我在这里,我想实施我的 inStB 函数,它不返回一个字符串的计数,它只是返回一个布尔值,如果搜索字符串是存在的。我经常需要这个函数,这使我的代码更干净。

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