Advertisement
dimipan80

Advanced Topics 16. Counting a Word in a Text

Jul 4th, 2014
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.04 KB | None | 0 0
  1. // Write a program that counts how many times a given word occurs in given text. The first line in the input holds the word. The second line of the input holds the text. The output should be a single integer number – the number of word occurrences. Matching should be case-insensitive. Note that not all matching substrings are words and should be counted. A word is a sequence of letters separated by punctuation or start / end of text.
  2.  
  3. namespace _16.CountingWordInText
  4. {
  5.     using System;
  6.  
  7.     public class CountingWordInText
  8.     {
  9.         public static void Main(string[] args)
  10.         {
  11.             checked
  12.             {
  13.                 Console.Write("Enter your counting Word: ");
  14.                 string countingWord = Console.ReadLine();
  15.                 Console.WriteLine("Enter your holds Text on single line!");
  16.                 string inputText = Console.ReadLine();
  17.                 if (countingWord != string.Empty && inputText != string.Empty)
  18.                 {
  19.                     char[] separators = new char[] { ' ', ',', ';', '-', ':', '"', '\'', '(', ')', '/', '!', '?', '.', '$', '@', '#', '%', '&', '\\', '[', ']', '{', '}', '|', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '*', '=' };                    
  20.                     string[] text = inputText.Split(separators, StringSplitOptions.RemoveEmptyEntries);
  21.                     int countWord = 0;
  22.                     for (int i = 0; i < text.Length; i++)
  23.                     {
  24.                         string currentWord = text[i];
  25.                         bool isEquals = countingWord.Equals(currentWord, StringComparison.OrdinalIgnoreCase);
  26.                         if (isEquals)
  27.                         {
  28.                             countWord++;
  29.                         }
  30.                     }
  31.  
  32.                     Console.WriteLine("The Given word occurs in given text {0} times !", countWord);
  33.                 }
  34.                 else
  35.                 {
  36.                     Console.WriteLine("Error! - Invalid Input!!!");
  37.                 }
  38.             }
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement