Imports System
Imports System.Text
Imports System.Collections.Generic
Module CommonWordsProgram
'
' Normalize a string:
' - Convert letters to lowercase
' - Replace any non-letter with a space
' This ensures consistent word comparison.
'
Private Function Normalize(input As String) As String
Dim sb As New StringBuilder(input.Length)
For Each ch As Char In input
If Char.IsLetter(ch) Then
sb.Append(Char.ToLower(ch))
Else
sb.Append(" "c)
End If
Next
Return sb.ToString()
End Function
'
' Extract words from a string.
'
' This function:
' - Normalizes the input
' - Splits on whitespace
' - Filters out empty entries
' - Returns a HashSet(Of String) for fast lookup and automatic duplicate removal
'
Private Function ExtractWords(input As String) As HashSet(Of String)
Dim normalized As String = Normalize(input)
Dim parts As String() = normalized.Split({" "c}, StringSplitOptions.RemoveEmptyEntries)
Dim words As New HashSet(Of String)(StringComparer.Ordinal)
For Each w In parts
words.Add(w)
Next
Return words
End Function
'
' Find common words between two strings.
'
' This function:
' - Extracts words from both strings
' - Uses set intersection for efficiency
' - Returns a new HashSet(Of String) containing the common words
'
Private Function FindCommonWords(a As String, b As String) As HashSet(Of String)
Dim wordsA = ExtractWords(a)
Dim wordsB = ExtractWords(b)
Dim common As New HashSet(Of String)(wordsA, StringComparer.Ordinal)
common.IntersectWith(wordsB)
Return common
End Function
Sub Main()
Dim s1 As String = "The quick brown fox jumps over the lazy dog."
Dim s2 As String = "A lazy dog sleeps while the quick fox runs away."
Dim common = FindCommonWords(s1, s2)
Console.WriteLine("Common words:")
For Each w In common
Console.WriteLine(w)
Next
End Sub
End Module
'
' run:
'
' Common words:
' the
' quick
' fox
' lazy
' dog
'