Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- class CountSubstringOccurrencesInText
- {
- //Write a program that finds how many times a substring is contained in a given text (perform case insensitive search).
- //Example: The target substring is "in". The text is as follows:
- //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.
- //The result is: 9.
- static void Main()
- {
- 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.";
- string substringToCount = "in";
- substringToCount = substringToCount.ToLowerInvariant();
- int counter = 0; //Stores the number of occurrences of the substring in the text
- int lastIndexOfSubstr = text.LastIndexOf(substringToCount);//Returns the index of the last occurrence of the substring in the text
- if (lastIndexOfSubstr == -1)//If there is no last index, then the substring doesn't exist in the text
- {
- Console.WriteLine("The substring '{0}' cannot be found in the text!", substringToCount);
- }
- else
- {
- for (int startIndex = 0; startIndex <= lastIndexOfSubstr; )//Cycle through each occurrence of the substring until the last occurrence is reached
- {
- 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
- counter++; //count it
- startIndex+= substringToCount.Length;//Increase the position for the next search
- }
- Console.WriteLine("The substring '{0}' has {1} occurrence/s/ in the text!", substringToCount, counter); //Print the result
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement