HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Creating new string with only distinct letters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
distinctnewcreatingwithonlystringletters

Problem

Aim: To have only one of each character on the Return string:

Public Shared Function CheckForDuplicates(ByVal vCharCheck As String) As String

    Dim vDeDuplicated As String = ""
    Dim i As Integer

    For i = 1 To vCharCheck.Length ' Count length of string

        'vDeDuplicate is blank to start so will always capture first character
        'vDeDuplicate is then checked against each character in the incoming string to see if it contains this character already
        'thus deduplicting the string

        If vDeDuplicated.Contains(Mid(vCharCheck, i, 1)) Then   
            'Check the new string to see if it exists, if it does it is not allowed 
        Else
            'The character is not found so we add it
            vDeDuplicated += Mid(vCharCheck, i, 1)
        End If

    Next

    Return vDeDuplicated
End Function

Solution

Of course you can eliminate the loop by using the Distinct method of the string, which won't care if the string is empty or not. Assuming vCharCheck is the input string, it would look something like this:

Return New String(vCharCheck.Distinct.ToArray)

Code Snippets

Return New String(vCharCheck.Distinct.ToArray)

Context

StackExchange Code Review Q#41165, answer score: 7

Revisions (0)

No revisions yet.