removing repeats from an array

  • Thread starter Thread starter WStoreyII
  • Start date Start date
W

WStoreyII

i have an array of string values

i have tried all day to figure a sub that will remove them but everything i
have tried only leaves me with one item in the array.

any ideas.

Thanks in advance

WStoreyII
 
* "WStoreyII said:
i have an array of string values

i have tried all day to figure a sub that will remove them but everything i
have tried only leaves me with one item in the array.

Loop through the strings, then add them to a hashtable (strings as key
and value). After doing that, put all values from the hashtable back in
an array.
 
WStoreyII,

Below is a sample VB.Net console application that copies only the non-repeating strings to a new array.

I hope it helps.


Imports System
Imports System.Collections

Public Class SamplesArray

Public Shared Sub Main()
Dim i As Integer
Dim j As Integer
' Creates and initializes a new Array
Dim myArr As [String]() = {"over", "fox", "lazy", "dogs", "brown", "the", "the", _
"brown", "the", "lazy", "jumped", "dogs", "The", "the", "fox", "over", _
"quick", "brown", "lazy", "dogs", "quick", "fox", "The", "fox", "The", _
"over", "jumped", "dogs", "over", "brown", "quick", "lazy", "jumped", _
"The", "jumped", "quick"}
Dim myArr2 As [String]()
ReDim myArr2(myArr.Length)

' Sorts the entire Array using the default comparer.
Array.Sort(myArr)
Console.WriteLine("After sorting the entire Array using the default comparer:")
PrintIndexAndValues(myArr)

myArr2(0) = myArr(0)
j = 0
For i = 1 To myArr.Length - 1
If (myArr2(j) <> myArr(i)) Then
j = j + 1
myArr2(j) = myArr(i)
End If
Next i
ReDim Preserve myArr2(j)
Console.WriteLine("New array with no duplicate values:")
PrintIndexAndValues(myArr2)
Console.ReadLine()

End Sub 'Main

Public Shared Sub PrintIndexAndValues(ByVal myArr() As [String])

Dim i As Integer
For i = 0 To myArr.Length - 1
Console.WriteLine(" [{0}] : {1}", i, myArr(i))
Next i
Console.WriteLine()

End Sub 'PrintIndexAndValues

End Class 'SamplesArray

Andrew Steenson [MSFT]
Developer Division Sustained Engineering Team
 
Back
Top