2009-12-07 44 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 
相关问题