Knowledge Required:
- Array
- String
Description:
Here is a function that extracts out the unique values from comma delimited string.
Public Function GetUnique( _
ByVal sStringToUse As String, _
Optional ByVal sSeperator As String = ",", _
Optional ByVal LimitWords As Integer = 0 _
) As String
Dim sStrings() As String
Dim sToRet As String = ""
sStrings = sStringToUse.Split(sSeperator)
Dim i As Integer = 0
For Each s As String In sStrings ' for each item in array
Dim sTrimed As String = s.Trim()
' if limit is supplied and also limit is NOT over
If Not (LimitWords < 1 OrElse i < LimitWords) Then Exit For
' if this item is NOT added previously
If sToRet.IndexOf(sTrimed, StringComparison.CurrentCultureIgnoreCase) < 0 Then
i += 1
sToRet &= sTrimed & "," ' add it in list
End If
Next
If sToRet.Length > 0 Then ' if items found
' return them
Return sToRet.ToString().Substring(0, sToRet.Length - 1)
Else ' else (item NOT found)
Return "" ' return empty string
End If
End Function
Usage:
Dim a As String
a = "computer,hardware,computer,software,hardware,tools,downloads,software"
Debug.Print(GetUnique(a))
Output:
computer,downloads,hardware,software,tools
No comments:
Post a Comment