Bruno
Bruno

Reputation: 6449

Find the first non-repeating character in a string in VB.NET

I need to write a function to find the first non-repeating character in a string in VB.NET. Does the code below look ok?

Module Module2

Sub Main()
    ' Unit test
    ' Pass string as argument.
    Console.WriteLine(nonRepeat("BBEEXEE")

End Sub

Function nonRepeat(ByVal aString As String) As String

    Dim repeated As Integer = 0

    For i = 0 To aString.Length-1

        repeated = 0

        For j = 0 To aString.Length-1

            ' If inner and outer For loops are on the same index then
            ' inner For loop moves to next index and compares character 
            ' with outer For loop character.
            ' If characters are equal then set repeated = 1 and Exit inner For loop.
            ' Otherwise, continue to find repeating character
            ' If reached end of string without finding repeating character
            ' then non-repeating character has been found and is returned.

            If ((i <> j) AndAlso (aString(i) = aString(j))) Then

                ' Found repeating character 
                repeated = 1

                Exit For

            End If

        Next

        If (repeated = 0) Then

            ' Found first non-repeating character
            Return aString(i)

        End If
    Next

    Return ("No Non-Reapeating character!")

End Function

End Module

Upvotes: 0

Views: 1635

Answers (3)

Andrew Paglusch
Andrew Paglusch

Reputation: 845

Dim str As String = "BBEEXEE"
    For Each ch As Char In str
        If str.Contains(ch & ch) = False Then
            'first non-repeating
            MsgBox("First non-repeating character is: " & ch)
            Exit For
        End If
    Next

Upvotes: 0

chrissie1
chrissie1

Reputation: 5029

A bit of linq could make this a lot shorter.

Imports System.Linq

Module Module1

  Sub Main()
    Console.WriteLine(FirstCharacterToNotRepeat(Nothing))
    Console.WriteLine(FirstCharacterToNotRepeat(""))
    Console.WriteLine(FirstCharacterToNotRepeat("BBEEXEE"))
    Console.WriteLine(FirstCharacterToNotRepeat("BBEEEE"))
    Console.WriteLine(FirstCharacterToNotRepeat("XBBEEEE"))
    Console.WriteLine(FirstCharacterToNotRepeat("BBEEEEX"))
    Console.WriteLine(FirstCharacterToNotRepeat("BBEEXEEACEED"))
    Console.ReadLine()
  End Sub

  Private Function FirstCharacterToNotRepeat(ByVal input As String) As String
    If String.IsNullOrEmpty(input) Then Return String.Empty
    Return (input.GroupBy(Function(x) x).Where(Function(x) x.Count = 1).Select(Function(x) x.First))(0)
  End Function
End Module

Upvotes: 1

competent_tech
competent_tech

Reputation: 44931

No, your code will throw exceptions because your loops will run out of data to process. Your loops need to end as .Length -1. Otherwise, it should work.

However, you could make it more efficient and handle edge cases:

    ' Don't bother checking if the string is empty
    If Not String.IsNullOrEmpty(asString) Then
        ' If the string is only a single character, just return it
        If asString.Length = 1 Then
            Return asString
        End If

        ' Create a collection that records the number of occurences for each character
        Dim cCharacterCounts As New System.Collections.Generic.Dictionary(Of Char, Integer)

        For Each cCharacter As Char In asString
            If cCharacterCounts.ContainsKey(cCharacter) Then
                ' If the character exists, increment its count
                cCharacterCounts(cCharacter) += 1
            Else
                ' Otherwise record the character as a new entry, initializing the count to 1
                cCharacterCounts.Add(cCharacter, 1)
            End If
        Next

        ' Now find the first character which only has a single count. This will be the first non-repeating value.
        For Each cCharacter As Char In cCharacterCounts.Keys
            If cCharacterCounts(cCharacter) > 1 Then
                Return cCharacter.ToString()
            End If
        Next
    End If

    ' Handle the case in which there is no non-repeating character
    Return String.Empty

Upvotes: 1

Related Questions