2016-09-20 158 views
0

我有2个文本框和一个按钮,当单击按钮时,我希望它将我创建的列表放入小写字母并检查每个字符串出现的出现次数。获取字符串列表中字符串的出现次数。

我的代码:

Private Sub FlatButton1_Click(sender As Object, e As EventArgs) Handles FlatButton1.Click 
    Dim count As Integer = 0 
    Dim userString As String = userInput.Text 
    userString = userString.ToLower() 
    Dim inputList As New List(Of String)(userString.Split(" ")) 

    While count <= inputList.Count - 1 
     output.Text &= inputList(count) & " Occurred: " & NEED TO GET OCCURRENCE & Environment.NewLine 
     count = count + 1 
    End While 
End Sub 

什么是保持计数为每个单词的最好方法?

感谢,

马特

回答

0

你可以使用字典来存储的话和他们的罪状:

Option Infer On 
' .... 
Dim s = "The only cat sat only on the cat mat" 
Dim d As New Dictionary(Of String, Integer) 

Dim ws = s.ToLower().Split(" "c) 

For Each w In ws 
    If d.ContainsKey(w) Then 
     d(w) += 1 
    Else 
     d.Add(w, 1) 
    End If 
Next 

For Each de In d 
    Console.WriteLine(String.Format("{0,-10}{1,2}", de.Key, de.Value)) 
Next 

Console.ReadLine() 

输出:

the  2 
only  2 
cat  2 
sat  1 
on   1 
mat  1 

(该下降计数只巧合)。

+0

什么是追加,为一个文本框的最佳方式? http://pastebin.com/vXmZk9a9 –

+0

@MeeMeme使用'output.AppendText(String.Format(“{0,-10} {1,2}”&VbCrLf,de.Key,de.Value))''而不是'Console.WriteLine(...)'行。 –

+0

该代码产生这个:http://s17.postimg.org/gby1qsie7/Capture.png –

1

您可以使用一个简单的LINQ表达式:

Dim userString As String = "How much wood would a woodchuck chuck if a woodchuck could chuck wood" 

Dim userStringGroupByWords = userString.Split(" ").GroupBy(Function(word) word) 

For Each word In userStringGroupByWords 
    Console.WriteLine($"Word: {word.Key}, Count: {word.Count}") 
    'Or Console.WriteLine("Word: {0}, Count: {1}", word.Key, word.Count) 
    'if you are not using VS 2015 and .NET >= 4.6 
Next 

输出:

Group: How, Count: 1 
Group: much, Count: 1 
Group: wood, Count: 2 
Group: would, Count: 1 
Group: a, Count: 2 
Group: woodchuck, Count: 2 
Group: chuck, Count: 2 
Group: if, Count: 1 
Group: could, Count: 1 
相关问题