Advertisement
sylviapsh

Count Substring Occurrences In Text

Jan 29th, 2013
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.82 KB | None | 0 0
  1. using System;
  2.  
  3. class CountSubstringOccurrencesInText
  4. {
  5.   //Write a program that finds how many times a substring is contained in a given text (perform case insensitive search).
  6.   //Example: The target substring is "in". The text is as follows:
  7.   //We are living in an yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.
  8.   //The result is: 9.
  9.  
  10.   static void Main()
  11.   {
  12.     string text = "We are living in an yellow submarine. We don't have anything else. Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days.";
  13.     string substringToCount = "in";
  14.     substringToCount = substringToCount.ToLowerInvariant();
  15.  
  16.     int counter = 0; //Stores the number of occurrences of the substring in the text
  17.     int lastIndexOfSubstr = text.LastIndexOf(substringToCount);//Returns the index of the last occurrence of the substring in the text
  18.  
  19.     if (lastIndexOfSubstr == -1)//If there is no last index, then the substring doesn't exist in the text
  20.     {
  21.       Console.WriteLine("The substring '{0}' cannot be found in the text!", substringToCount);
  22.     }
  23.     else
  24.     {
  25.       for (int startIndex = 0; startIndex <= lastIndexOfSubstr; )//Cycle through each occurrence of the substring until the last occurrence is reached
  26.       {
  27.         startIndex = text.ToLowerInvariant().IndexOf(substringToCount, startIndex); // search for the next occurrence and return its index. The text is lowered so that all occurences are captured
  28.         counter++; //count it
  29.         startIndex+= substringToCount.Length;//Increase the position for the next search
  30.       }
  31.  
  32.       Console.WriteLine("The substring '{0}' has {1} occurrence/s/ in the text!", substringToCount, counter); //Print the result
  33.     }
  34.   }
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement