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

73
什么是在字符串中计算特定字符出现次数的最简单方法?
也就是说,我需要编写一个名为countTheCharacters()的函数,以便进行计数。
str = "the little red hen"
count = countTheCharacters(str,"e") ' Count should equal 4
count = countTheCharacters(str,"t") ' Count should equal 3

最快的方法不是使用字符串。如果您真的对速度感兴趣,应该寻找其他东西。 - habakuk
1
@habakuk,除了“小红母鸡”之外,OP可以使用哪些非字符串值? - johny why
26个回答

2

使用正则表达式...

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

2
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

2

当我发现这个解决方案时,我正在寻找的内容与要计数的字符串长度超过一个字符略有不同,因此我想出了这个解决方案:

    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

1

另一种可能性是使用Split进行工作:

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

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

1

我使用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');

1
我在下面发布了一个VB.NET等效的内容。 - MattB

1

这么简单的东西需要如此庞大的代码:

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

0

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

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。

0
我找到了最好的答案:P:
String.ToString.Count - String.ToString.Replace("e", "").Count
String.ToString.Count - String.ToString.Replace("t", "").Count

0

var charCount = "带有句点的字符串...".Count(x => '.' == x);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接