星期三, 8月 24, 2016

[LINQ] 目標字串在文字內容出現次數

練習這篇 MSDN 文章 - How to: Count Occurrences of a Word in a String (LINQ)
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            // 字串內容
            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 SearchTarget = "data";

            // 目標字串出現在字串內容多少次
            int counts = text
                .Split(
                    new char[] { '.', '?', '!', ' ', ';', ':', ',' } , 
                    StringSplitOptions.RemoveEmptyEntries)
                .Where(word => word.ToLowerInvariant() == SearchTarget.ToLowerInvariant())
                .Count();

            Console.WriteLine($"{SearchTarget} 字串,在文字內容中出現 {counts} 次");
        }
    }
}
[LINQ] 目標字串在文字內容出現次數

沒有留言:

張貼留言