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();
}
}
}
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.
your tutorial finds “character occurrences” within a string! kindly update the code for finding the “string occurrences” or change the title.