就视觉基础而言,我是一个完全的菜鸟。 在课堂上我需要做以下几点:“编写一个程序,要求用户输入一个句子,然后记录字母表中每个字母出现的次数。”
我如何计算字符串中出现的次数?
感谢并抱歉这个noob问题。
答案 0 :(得分: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,但我认为你可以尝试
Dim s As String = "tafata"
Dim t = From c In s _
Group c By c Into Group _
Select Group
答案 1 :(得分:1)
正如Dave所说,最简单的解决方案是拥有一个长度为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
答案 2 :(得分: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
答案 3 :(得分:0)
我会计算并删除第一个字符的每个实例,并重复直到没有剩下的字符。然后显示检测到的每个字符的计数。除非你知道字符的可能范围小于句子的长度,否则比为每个可能的字符循环一次要好得多。
答案 4 :(得分: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
答案 5 :(得分:0)
from itertools import groupby
sentence = raw_input("Your sentence:")
for char,group in groupby(sorted(sentence.lower())):
print(char+": "+`len(list(group))`)