如何查找字符串中所有单词的出现次数

时间:2015-03-19 05:04:30

标签: .net vb.net string string-parsing

标题说明了这一点,我如何找到一个单词出现在字符串中的次数。我不知道用户会输入什么,所以我不能通过使用案例进行测试,任何人都可以帮忙吗?

我还可以只提取重要的单词吗?

例如字符串"testing apples testing"

它应该告诉我"testing"出现2次,"apples" 1次,然后返回包含{"testing","apples"}的列表

2 个答案:

答案 0 :(得分:2)

  1. 您可以通过用空白字符拆分字符串来实现此目的
  2. 计算foreach块中的单词
  3. 从此代码中获取帮助

    private void countWordsInString(string yourString, Dictionary<string, int> words)
    { 
      var text = yourString.ToString();
    
      var allwords = Regex.Split(text, @"\W");
    
      foreach (Match match in allwords.Matches(text))
      {
        int currentCount=0;
    
        words.TryGetValue(match.Value, out currentCount);
    
        currentCount++;
    
        words[match.Value] = currentCount;
      }
    }
    
    var words = new Dictionary<string, int>(StringComparer.CurrentCultureIgnoreCase);
    
    countWordsInString("testing apples testing", words);
    

    单词[&#34; apple&#34;]返回&#34; apple&#34;在你的字符串中。

答案 1 :(得分:1)

这是一个巧妙的oop方法:

Option Strict On
Option Explicit On
Option Infer Off
Public Class Form1
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim testString As String = "testing apples testing dog cat dog apples testing cat dog log frog log"
        Dim occurrences As List(Of ItemOccurrence) = GetOccurrence(testString)
        For Each iO As ItemOccurrence In occurrences
            MsgBox(iO.ToString)
        Next
    End Sub
    Public Function GetOccurrence(source As String) As List(Of ItemOccurrence)
        Dim parts As List(Of String) = source.Split({" "c}, StringSplitOptions.RemoveEmptyEntries).ToList
        Dim results As New List(Of ItemOccurrence)
        For Each Str As String In parts
            Dim match As ItemOccurrence = Nothing
            For i As Integer = 0 To results.Count - 1
                If results(i).Text.ToLower = Str.ToLower Then match = results(i)
            Next
            If match Is Nothing Then
                results.Add(New ItemOccurrence(Str))
            Else
                match.Count += 1
            End If
        Next
        Return results
    End Function
    Public Class ItemOccurrence
        Public Property Text As String = String.Empty
        Public Property Count As Integer = 1
        Sub New(text As String)
            Me.Text = text
        End Sub
        Public Shadows Function ToString() As String
            If Me.Count = 1 Then Return String.Format("""{0}"" occured {1} time in the string.", Text, Count)
            Return String.Format("""{0}"" occured {1} times in the string.", Text, Count)
        End Function
    End Class
End Class