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
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: