.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Melody Anderson

Home >> Code Snippets >> LINQ >> Post New Resource Bookmark and Share   

 Subscribe to Code Snippets

Count Occurrences of a Word in a String

Posted By:abhays       Posted Date: July 10, 2014    Points: 40    Category: LINQ    URL: http://www.dotnetspark.com  

Count Occurrences of a Word in a String

Below code block shows how to use a LINQ query to count the occurrences of a specified word in a stringv


using System;
using System.Linq;
namespace StringCount
    class Program
        static void Main(string[] args)
            string text = "This is a pen.This is a cat.This is a room.This is an elephant.You say this ";
            string searchTerm = "this";
            string[] source = text.Split(new char[] { '.' ,' ' }, StringSplitOptions.RemoveEmptyEntries);
            var matchQuery = from word in source
                             where word.ToLowerInvariant() == searchTerm.ToLowerInvariant()
                             select word;
            // Count the matches, which executes the query. 
            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");



Further Readings:


No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More code samples in C#, ASP.Net, Vb.Net and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend