다음을 통해 공유


방법: 문자열에서 단어가 나오는 횟수 세기(LINQ)

업데이트: 2007년 11월

이 예제에서는 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.
class CountWords
{
    static void Main()
    {
        string text = @"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.";

        string searchTerm = "data";

        //Convert the string into an array of words
        string[] source = text.Split(new char[] { '.', '?', '!', ' ', ';', ':', ',' }, StringSplitOptions.RemoveEmptyEntries);

        // Create and execute the query. It executes immediately 
        // because a singleton value is produced.
        // Use ToLowerInvariant to match "data" and "Data" 
        var matchQuery = from word in source
                         where word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
                         select word;

        // Count the matches.
        int wordCount = matchQuery.Count();
        Console.WriteLine("{0} occurrences(s) of the search term \"{1}\" were found.", wordCount, searchTerm);

        // Keep console window open in debug mode
        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
    }
}
/* Output:
   3 occurrences(s) of the search term "data" were found.
*/

코드 컴파일

  • .NET Framework 버전 3.5를 대상으로 하는 Visual Studio 프로젝트를 만듭니다. 기본적으로 프로젝트에는 System.Core.dll에 대한 참조 및 System.Linq 네임스페이스에 대한 using 지시문(C#) 또는 Imports 문(Visual Basic)이 있습니다. C# 프로젝트에서는 System.IO 네임스페이스에 대한 using 지시문을 추가합니다.

  • 프로젝트에 이 코드를 복사합니다.

  • F5 키를 눌러 프로그램을 컴파일하고 실행합니다.

  • 아무 키나 눌러 콘솔 창을 닫습니다.

참고 항목

개념

LINQ 및 문자열