Search code examples
stringvbscriptqtphp-uft

How to find repeated sub string in a main string using VBScript


How to find repeated sub string in a main string using VBScript?

For example, if the string is

str = "Google mail, Google Maps, Google drive, Google music, Google play, Google office"

I need the the substring which is repeated in above string. Also its count.

Thanks


Solution

  • This will give the count of all words in a given substring.

     str = "Google mail, Google Maps, Google drive, Google music, Google play, Google office"
    
        Function RemoveDuplicates(str)
          If Trim(str) = "" Then
            RemoveDuplicates = Array()
            Exit Function
          End If
    
          Set d = CreateObject("Scripting.Dictionary")
          d.CompareMode = vbTextCompare  'make dictionary case-insensitive
    
          For Each elem In Split(str)
            d(elem) = True
          Next
    
          RemoveDuplicates = d.Keys
        End Function
    
        sUniques = RemoveDuplicates(str)
    
        For k = 0 To UBound(sUniques)
                iCount = len(str) - len(replace(str, sUniques(k), ""))
                msgbox "The string " & sUniques(k) & " appeared " & iCount/len(sUniques(k)) & " times"
        Next
    

    Using First function from https://stackoverflow.com/a/20310733/2571523