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 John Tel on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

removing duplicate characters in a string 3

Status
Not open for further replies.

drkclw

Programmer
Feb 17, 2004
7
US
I need a way to go through an array and remove duplicate chars. I'm working with strings that contain only numbers from 0 to 27.
SampleStr = 0 2 2 5 8 9 9 12 15 27 27
I would like that to become:
NewStr = 0 2 5 8 9 12 15 27
 
Hi,

here's a way
Code:
Function NoDups(s As String)
    Dim ary, bNoMatch As Boolean
    ary = Split(s, " ")
    x = ""
    For i = LBound(ary) To UBound(ary)
        bNoMatch = True
        For j = i + 1 To UBound(ary)
            If ary(i) = ary(j) Then
                bNoMatch = False
                Exit For
            End If
        Next
        If bNoMatch Then x = x & " " & ary(i)
    Next
    NoDups = x
End Function
:)

Skip,

Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Hi drkclw,

If your numbers are in sequence as you show, I think this will do it for you ..

[blue]
Code:
For Each n in Split(SampleStr)
    If InStr(NewStr, n & " ") = 0 then Newstr = Newstr & n & " "
Next
NewStr = Trim(NewStr)
[/blue]

If they're not in sequence, or there are multiple spaces between strings it will need a bit of tweaking. Please post back if you want any help with that.

Enjoy,
Tony

------------------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading FAQ222-2244 before you ask a question.
 
Tony,
the code works great, my numbers are in a squence.

I have another question.
Is it possible to go through the original SampleStr and replace a 3, 4, or 5 with a 2? How would i do this without changing a number like 24 into 22? I tried:
For i = 3 to 5
NewStr = replace (SampleStr, i, 2)
Next
but it turns my numbers like 24 into 22's
 
Adapted from Tony's code:
Code:
For Each n in Split(SampleStr)
  If n >= 3 And n <= 5 Then n = 2
  Newstr = Newstr & n & &quot; &quot;
Next
NewStr = Trim(NewStr)

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884
 
Hi drkclw,

Another way - looking for space delimited strings ..

[blue]
Code:
For i = 3 to 5
    NewStr = Trim(Replace(&quot; &quot; & NewStr & &quot; &quot;,&quot; &quot; & i & &quot; &quot;,&quot; &quot; & 2 & &quot; &quot;))
Next
[/blue]

Enjoy,
Tony

------------------------------------------------------------------------------------------------------
We want to help you; help us to do it by reading FAQ222-2244 before you ask a question.
 
Thanks for all the help. Both pieces of code work great.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top