VB.NETで文字列内の最初の非繰り返し文字を検索する

私はVB.NETで文字列の最初の非反復文字を見つけるための関数を書く必要があります。下のコードは大丈夫ですか?

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
ベストアンサー

linqのビットがこれよりずっと短くなる可能性があります。

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

コメントする

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です