다음을 통해 공유


방법: 문자열에서 단어의 발생 횟수 계산(LINQ)(Visual Basic)

이 예제에서는 LINQ 쿼리를 사용하여 문자열에서 지정된 단어의 발생 횟수를 계산하는 방법을 보여 줍니다. 개수를 수행하기 위해 먼저 메서드를 Split 호출하여 단어 배열을 만듭니다. 메서드에 성능 비용이 있습니다 Split . 문자열에 대한 유일한 연산이 단어 수를 계산하는 것이라면, 대신 Matches 또는 IndexOf 메서드를 사용하는 것을 고려하십시오. 그러나 성능이 중요한 문제가 아니거나 다른 유형의 쿼리를 수행하기 위해 문장을 이미 분할한 경우 LINQ를 사용하여 단어나 구의 개수를 계산하는 것이 좋습니다.

예시

Class CountWords

    Shared Sub Main()

        Dim text As String = "Historically, the world of data and the world of objects" &
                  " have not been well integrated. Programmers work in C# or Visual Basic" &
                  " and also in SQL or XQuery. On the one side are concepts such as classes," &
                  " objects, fields, inheritance, and .NET Framework APIs. On the other side" &
                  " are tables, columns, rows, nodes, and separate languages for dealing with" &
                  " them. Data types often require translation between the two worlds; there are" &
                  " different standard functions. Because the object world has no notion of query, a" &
                  " query can only be represented as a string without compile-time type checking or" &
                  " IntelliSense support in the IDE. Transferring data from SQL tables or XML trees to" &
                  " objects in memory is often tedious and error-prone."

        Dim searchTerm As String = "data"

        ' Convert the string into an array of words.
        Dim dataSource As String() = text.Split(New Char() {" ", ",", ".", ";", ":"},
                                                 StringSplitOptions.RemoveEmptyEntries)

        ' Create and execute the query. It executes immediately
        ' because a singleton value is produced.
        ' Use ToLower to match "data" and "Data"
        Dim matchQuery = From word In dataSource
                      Where word.ToLowerInvariant() = searchTerm.ToLowerInvariant()
                      Select word

        ' Count the matches.
        Dim count As Integer = matchQuery.Count()
        Console.WriteLine(count & " occurrence(s) of the search term """ &
                          searchTerm & """ were found.")

        ' Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.")
        Console.ReadKey()
    End Sub
End Class
' Output:
' 3 occurrence(s) of the search term "data" were found.

코드 컴파일

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

참고하십시오