Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function to remove duplicate words in a single string

Status
Not open for further replies.

DRH192

Programmer
Apr 25, 2005
96
GB
Hello everyone,

Does anybody have a good function written that will allow a string to be passed to it and return the same string but with any duplicating words removed to leave just the first occurance of the word?

I.e. if I passed in "I need need some help" it will return "I need some help"

Many Thanks
 
Code:
Function RemoveDupWords(myStr As String) As String
Dim s() As String
Dim n As Integer
Dim r As String

If Len(myStr) = 0 Then Exit Function

s = Split(Replace(myStr, "  ", " "), " ")

r = s(0)

For n = 1 To UBound(s)
   If s(n - 1) <> s(n) Then
      r = r & s(n)
   End If
Next

RemoveDupWords = r

End Function
 
Golom,
Your code dropped the spaces between the words.
Code:
Function RemoveDupWords2(myStr As String) As String
Dim s() As String
Dim n As Integer

If Len(myStr) = 0 Then Exit Function

s = Split(myStr, " ")

For n = 1 To UBound(s)
   If s(n - 1) = s(n) Then
      s(n) = ""
   End If
Next

RemoveDupWords2 = Replace(Join(s, " "), "  ", " ")

End Function

Hope this helps,
CMP

[small]For the best results do what I'm thinking, not what I'm saying.[/small]
(GMT-07:00) Mountain Time (US & Canada)
 
CautionMP

You're right! ... Too early in the morning I guess.
Thanks for spotting that.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top