2011-03-04 422 views
52

計算字符串中特定字符出現次數的最簡單方法是什麼?計算字符串中特定字符的出現次數

即我需要編寫一個函數countTheCharacters(),使

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

最快的方法是不要使用字符串。如果你真的對速度感興趣,你應該尋找其他的東西。 – habakuk 2016-02-19 10:13:19

+0

@habakuk,OP可以用什麼非字符串值代替「小紅母雞」? – 2016-03-08 22:10:43

+0

@johnywhy使用StringBuilder。請參閱https://msdn.microsoft.com/de-de/library/system.text.stringbuilder%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-11 – habakuk 2016-03-09 21:43:53

回答

60

最直接的方式是簡單地通過字符串中的字符循環:

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

我來這裏尋找*最快*的方法,不一定是最優雅的一個。這很快,但通過使用「For i as Integer = 0 value.Length - 1」,而不是For Each循環,可以快10%左右。 – NightOwl888 2014-08-13 19:34:06

+0

''Count'不是'String'的成員.' – Panzercrisis 2014-10-14 14:57:18

+0

@Panzercrisis:Count計數方法是'IEnumerable '的擴展方法,'String'實現'IEnumerable '。如果你得到這樣的編譯器錯誤,你會錯過頁面頂部的'using System.Linq;'引用。 – Guffa 2014-10-14 17:14:05

1

另一種可能性是與斯普利特的工作:

Dim tmp() As String 
tmp = Split(Expression, Delimiter) 
Dim count As Integer = tmp.Length - 1 
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這。

4

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

這裏是直接代碼解決了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 
+6

-1抱歉,不僅僅是_very_冗長,[您正在使用'GOTO's!](http://www.u .arizona.edu /〜rubinson/copyright_violations/Go_To_Considered_Harmful.html) – Basic 2012-04-03 22:30:49

3

將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()) 
+0

謝謝,我選擇了這個版本。似乎也非常快。我實際上是在文本字符串中搜索CR和/或LF,以及頻率,以便我可以調整GridView中文本框的大小和高度以支持輸出。 – htm11h 2015-03-03 20:46:49

28

你可以試試這個

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

用Len(testCharStr)和Ceil來分隔你的答案,以此來處理字符串的出現。 – 2013-02-11 10:17:25

+0

這個方法的好處是,它使用非常基本的fx。沒有LINQ,RegEx或其他額外的庫。可以用各種語言輕鬆複製。 – 2016-03-08 22:13:27

2
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") 
+1

在Stack Overflow上,您可以使用編輯器中的{}按鈕來格式化代碼。這次我把它作爲一個編輯。 – Flexo 2012-06-16 11:02:01

56

這是簡單的方式

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

如果起始字母或/和endletter是要計數的數字,那麼這並不總是正確的數字 – Reman 2013-07-23 12:11:37

+0

@Remonn它總是給我正確的數字。不計算開始/結束字母的唯一方法是將SplitStringOptions.RemoveEmptyEntries作爲第二個參數傳遞給Split() – alldayremix 2013-09-06 17:46:03

+0

這很簡單,但它會創建一些甚至不用於任何內容的字符串。 – Guffa 2014-10-14 19:17:28

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

我建議你這樣做:

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

您還可以使用.Split("e").Count - 1.Split("t").Count - 1 respetivelly,但它給錯誤的價值觀,如果你,比如有一個E或處的String

+1

這個vb.net是什麼?我沒有安裝visual studio,但dotnetfiddle.net和ideone.com報告「'count'不是'String'的成員。」 – 2016-03-08 22:45:50

0

開始我找到了最好的答案:P:

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

使用正則表達式...

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

我使用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 2014-07-21 21:38:00

-2

使用:

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

這甚至不會編譯。 – 2014-12-19 06:25:23

+0

這是什麼?它甚至不編譯,即使使用'Explicit Off'和'Option Strict Off'。 – 2017-04-01 17:32:08

+0

它是Basic的其他形式,如[Visual Basic 6.0](http://en.wikipedia.org/wiki/Visual_Basic#Timeline)或[VBScript](http://en.wikipedia.org/wiki/VBScript )?問題是關於[VB.NET](http://en.wikipedia.org/wiki/Visual_Basic_.NET)。 – 2017-04-01 17:39:30

2

我認爲這將是最簡單的:

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

下面是一個簡單的版本。

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

上面會給你字符串中a的個數。如果你想忽略大小寫:

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

或者,如果你只是想算字母:

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

給它一個鏡頭!

+0

這看起來不像vb.net解決方案。 – Jonny 2017-01-25 12:22:49

+0

如何?它應該工作。你試過了嗎? – MattB 2017-02-23 17:37:58

+0

這是一個非常VB.NET的解決方案! – Adam 2017-04-24 10:48:45

-3
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 
+0

看起來像你打算髮布這[在這裏](http://stackoverflow.com/questions/9969824/vb-net-need-text-box-to-only-accept-numbers),雖然你已經發布了一個[答案](http://stackoverflow.com/a/24908847/301857)那裏。 – 2014-12-19 06:17:47

0

用途:

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

我以前strin的變種來處理很長的文本。根據用戶設置,拆分可以是基於零的或基於一個的,並且減去它可以確保正確的計數。

爲了保持代碼的簡潔,我沒有包含對strcount的測試長於strin

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

什麼巨大的代碼這麼簡單的東西:

在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

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

3

謝謝,@guffa。在一行中執行,或者在.NET中執行更長的語句的能力非常方便。此VB.NET示例計算LineFeed字符的數量:

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

j返回MyString中LineFeeds的數量。

0

我使用以下函數。它不是最高效的內存,但它很容易理解,支持多種比較方法,只有4行,速度很快,大多數在VBA中也可以工作,不僅可以找到單個字符,而且還可以找到任何搜索字符串(我經常搜索VbCrLf (一個或多個))。

唯一缺少的是從一個不同的「開始」開始搜索能力

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 
相關問題