2009-12-07 45 views
0

就視覺基本而言,我是一個總noob。 在課堂上我需要做以下工作:「編寫一個程序,請求用戶輸入一個句子,然後記錄每個字母出現的次數。」字符串中出現次數

我該如何計算字符串中出現的次數?

謝謝併爲noob問題抱歉。

回答

1

正如戴夫說,最簡單的解決辦法是將具有通過所述字符串中的每個字符長度26(英語)的陣列,並循環,遞增正確的數組元素。您可以使用每個字符的ASCII值,以確定它是字母,然後按字母的ASCII數字轉換成相應的索引號:

'Dimension array to 26 elements 
Dim LetterCount(0 to 25) As Long 

'Temporary index number 
Dim tmpIdx As Long 

'Temporary character 
Dim tmpChar as String 

'String to check 
Dim checkStr As String 
checkStr = "How many of each letter is in me?" 

'Change all letters to lower case (since the upper case 
'of each letter has a different ASCII value than its 
'lower case) 
checkStr = LCase(checkStr) 

'Loop through each character 
For n = 1 to Len(checkStr) 

    'Get current character 
    tmpChar = Mid(checkStr, n, 1) 

    'Is the character a letter? 
    If (Asc(tmpChar) >= Asc("a")) And (Asc(tmpChar) <= Asc("z")) Then 

    'Calcoolate index number from letter's ASCII number 
    tmpIdx = Asc(tmpChar) - Asc("a") 

    'Increase letter's count 
    LetterCount(tmpIdx) = LetterCount(tmpIdx) + 1 

    End If 

Next n 

'Now print results 
For n = 0 to 25 
    Print Chr(Asc("a") + n) & " - " & CStr(LetterCount(n)) 
Next n 
4

循環的字符,並添加到列表中

Dim s As String = "tafata" 
Dim count As New Dictionary(Of Char, Integer)() 
For i As Integer = 0 To s.Length - 1 
    count(s(i)) = (If(count.ContainsKey(s(i)), count(s(i)) + 1, 1)) 
Next 

還沒有使用LINQ是mutch工作,但我認爲你可以嘗試

Dim s As String = "tafata" 
Dim t = From c In s _ 
Group c By c Into Group _ 
Select Group 
+0

避風港還沒有時間嘗試它,但感謝代碼。 – Dylan 2009-12-07 21:13:26

+0

問題標記爲vb,此代碼是C#。 – ephemient 2009-12-07 22:20:52

0

我會數和刪除的第一個字符的每個實例,並重復,直到沒有剩下的字符。然後顯示檢測到的每個字符的計數。除非你知道可能的字符範圍小於句子的長度,否則比對每個可能的字符循環一次要好得多。

0
Imports System.Linq 
Dim CharCounts = From c In "The quick brown fox jumped over the lazy dog." _ 
       Group c By c Into Count() _ 
       Select c, Count 
+0

'跳'' - >'跳''否則'''沒有測試:-) – wqw 2012-05-16 08:54:31

0
from itertools import groupby 
sentence = raw_input("Your sentence:") 
for char,group in groupby(sorted(sentence.lower())): 
    print(char+": "+`len(list(group))`) 
1

快速和骯髒的方式:

Public Function CountInStr(ByVal value As String, ByVal find As String, Optional compare As VbCompareMethod = VbCompareMethod.vbBinaryCompare) As Long 
    CountInStr = (LenB(value) - LenB(Replace(value, find, vbNullString, 1&, -1&, compare))) \ LenB(find) 
End Function 
相關問題