using System.Collections.Generic;
using System.Threading.Tasks;
public static void Main()
Console.WriteLine("Please enter a string to be searched: ");
var searchString = Console.ReadLine();
while (string.IsNullOrEmpty(searchString))
Console.WriteLine("Error");
Console.WriteLine("Search string can not be empty");
Console.WriteLine("########################################");
Console.WriteLine("Please enter another value for the search string");
searchString = Console.ReadLine();
Console.WriteLine("Please enter the length for a random pattern to find.");
while (!uint.TryParse(Console.ReadLine(), out patternLength) || !Enumerable.Range(1, searchString.Length).Contains((int)patternLength))
Console.WriteLine("Error");
Console.WriteLine("Pattern length must be a postive integer");
Console.WriteLine("(1 to 4,294,967,295 and less than or equal to search string length {0}) please try another value.", searchString.Length);
Console.WriteLine("Pattern Results:");
var patternsFound = searchString.FindOccurences((int)patternLength);
if (patternsFound.Count > 0)
foreach (var patternFound in searchString.FindOccurences((int)patternLength))
Console.WriteLine("Pattern: \"{0}\", Occurrences: \"{1}\"", patternFound.Key, patternFound.Value);
Console.WriteLine("No patterns found!");
Console.WriteLine("Press any key to exit");
public static class StringExtenstions
public static Dictionary<string, int> FindOccurences(this String str, int patternLength)
var matchedPatterns = new Dictionary<string, int>();
var subStrings = Enumerable.Range(0, str.Length - (patternLength - 1)).Select(i => str.Substring(i, patternLength)).ToArray();
Parallel.ForEach(subStrings, substring =>
int startingIndex = 0, occurences = 0;
if (str.Contains(substring))
while ((startingIndex = str.IndexOf(substring, startingIndex, StringComparison.Ordinal)) < str.Length)
startingIndex += substring.Length;
if (!matchedPatterns.ContainsKey(substring) && occurences > 1)
matchedPatterns.Add(substring, occurences);