-2

The titles says it all, how do i find how many times a word comes out in a string. I have no idea what the user will input, so i cant test it by using case, can anyone help?

Can i also extract only the important words?

For example the string "testing apples testing"

It should tell me that "testing" came out 2 times, "apples" 1 time and then return a list with {"testing","apples"}

helb
  • 7,609
  • 8
  • 36
  • 58

2 Answers2

2
  1. You can do this by Splitting the string by white-space characters
  2. counting words in foreach block

get help from this code

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);

words["apple"] returns the number of times that "apple" is in your string.

kashif181
  • 315
  • 2
  • 11
1

Here's a neat oop approach for you:

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
Paul Ishak
  • 1,093
  • 14
  • 19