다음을 통해 공유


문자열에서 문자 조회하는 방법 (LINQ) (Visual Basic)

클래스는 String 제네릭 IEnumerable<T> 인터페이스를 구현하므로 모든 문자열을 문자 시퀀스로 쿼리할 수 있습니다. 그러나 LINQ의 일반적인 사용은 아닙니다. 복잡한 패턴 일치 작업의 경우 클래스를 Regex 사용합니다.

예시

다음 예제에서는 문자열을 쿼리하여 문자열에 포함된 숫자 수를 확인합니다. 쿼리는 처음 실행된 후 "다시 사용"됩니다. 이는 쿼리 자체가 실제 결과를 저장하지 않기 때문에 가능합니다.

Class QueryAString

    Shared Sub Main()

        ' A string is an IEnumerable data source.
        Dim aString As String = "ABCDE99F-J74-12-89A"

        ' Select only those characters that are numbers
        Dim stringQuery = From ch In aString
                          Where Char.IsDigit(ch)
                          Select ch
        ' Execute the query
        For Each c As Char In stringQuery
            Console.Write(c & " ")
        Next

        ' Call the Count method on the existing query.
        Dim count As Integer = stringQuery.Count()
        Console.WriteLine(System.Environment.NewLine & "Count = " & count)

        ' Select all characters before the first '-'
        Dim stringQuery2 = aString.TakeWhile(Function(c) c <> "-")

        ' Execute the second query
        For Each ch In stringQuery2
            Console.Write(ch)
        Next

        Console.WriteLine(System.Environment.NewLine & "Press any key to exit")
        Console.ReadKey()
    End Sub
End Class
' Output:
' 9 9 7 4 1 2 8 9
' Count = 8
' ABCDE99F

코드 컴파일

Visual Basic 콘솔 애플리케이션 프로젝트를 만들어서, System.Linq 네임스페이스에 대한 Imports 문을 추가합니다.

참고하십시오