计算数组中的不同字符

时间:2015-06-09 04:04:30

标签: vb.net

我见过类似这个的各种线程,但没有一个真正符合我的特定需求。我在本周末有一项作业,我认为我即将完成,但似乎无法在我的代码中找到我的错误。说明是采用用户输入的句子,短语或单词,并计算每个字母的出现次数,并将字母和出现次数输出到屏幕。我可以从任何给定的字符串中获取不同的字母,但是我似乎无法准确计算出现次数。我一直以字符串中的字母索引1结尾,或者这个代码片段显示为随机数。

Sub charCount()

    'Declare variables
    Dim UserPhrase As String = input.Text
    Dim charArray() As String = IO.File.ReadAllLines("Alphabet.txt")
    Dim count As Integer = 0
    Dim UserArray() As Char = UserPhrase.ToCharArray()

    'Find each letter in the string
    Dim letterQuery = From letter In charArray
                      Select letter

    'Count number of occurrences of each letter
    For Each letter In letterQuery
        If UserArray.Contains(letter) Then
            For Each c As Char In UserArray
                count = count + 1
            Next
            output.Items.Add(letter & "    " & count)
        End If
    Next
End Sub

非常感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:-1)

老实说,我不知道你在那里做了什么,但这与以下内容一样简单:

var count = File.ReadAllLines("file.txt").SelectMany(s=>s).Distinct().Count();

答案 1 :(得分:-1)

我在这里添加了评论:

'Count number of occurrences of each letter
For Each letter In letterQuery
    If UserArray.Contains(letter) Then
        For Each c As Char In UserArray
            'here you should add comparing c to letter. If equal then increment
            count = count + 1
        Next
        output.Items.Add(letter & "    " & count)
        'here you should reset counter to 0
    End If
Next