在字符串列表中出现字符串。

时间:2016-09-20 10:42:41

标签: vb.net

我有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

对每个单词进行计数的最佳方法是什么?

谢谢,

马特

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

(递减计数只是巧合。)