Count the Occurrences of String within another String in C#

Published on October 13, 2013 by abundantcode

Filed under C#

Last modified October 13, 2013

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 0 (0 votes)

This article have been viewed 4637 times

Do you want to find the number of occurrences of a string within a string in C#? This article will explain how to do it.

How would you count occurrences of a string within a string (C#)?

For example, assume that the main string is “Abundantcode is a programming, soucrecode, technology related website”. If we need to find the number of occurrences of the comma (,) from the above string, below is a sample code snippet demonstrating how to get it.

using System;

using System.Collections.Generic;

using System.Data;

using System.IO;

using System.Linq;

namespace AbundantCode

{

internal class Program

{

// How to Count the Occurences of String within another String in C#

private static void Main(string[] args)

{

string MainString = "Abundantcode is a programming , sourcecode , technology related website";

int TotalStringOccurences = MainString.Count(f => f == ',');

Console.WriteLine(TotalStringOccurences);

Console.ReadKey();

}

}

}

Count the Occurrences of String within another String in C#

0saves
If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

2 Comments

  1. Johnny Boy

    LINQ is the *slowest* way to do anything in C#. If you’re interested in the *fastest* way, check out this blog: http://blogs.davelozinski.com/curiousconsultant/csharp-net-fastest-way-to-check-if-a-string-occurs-within-a-string

    It benchmarks about a dozen different ways to count the number of times a string occurs in a string.

    April 13, 2014 - 3:46 pm – Reply

  2. Priya

    your tutorial finds “character occurrences” within a string! kindly update the code for finding the “string occurrences” or change the title.

    April 19, 2015 - 9:16 pm – Reply

Leave a Comment


x

You might be Interested in these Posts

C# and Lambda - Finding all the elements of an integer array less than 35

Here's a sample code snippet demonstrating how to find all the elements of an integer array that is ...

C# and LINQ - Finding all the elements of an integer array less than 35

Here's a sample code snippet demonstrating how to find all the elements of an integer array that is ...

How to get the CommandLine of the Current Application in C# ?

You might need to get the information that contains the commandline which is used to execute the cur...