Подсчитать сколько раз в текст1 встречается слово - C#

Узнай цену своей работы

Формулировка задачи:

Помогите сделать все эти задания, сам я не могу. Вот задания: 1. В тексте1 ввести любую фразу. В текст2 ввести слово. Подсчитать сколько раз в текст1 встречается слово, заданное в текст2.

Решение задачи: «Подсчитать сколько раз в текст1 встречается слово»

textual
Листинг программы
  1. using System;
  2. using System.Diagnostics;
  3. using System.Linq;
  4.  
  5. namespace ConsoleAppExperiments
  6. {
  7.     class TimeMesurer : IDisposable
  8.     {
  9.         private Stopwatch stopwatch = new Stopwatch();
  10.  
  11.         public TimeMesurer()
  12.         {
  13.             this.stopwatch.Start();
  14.         }
  15.         public void Dispose()
  16.         {
  17.             this.stopwatch.Stop();
  18.             Console.WriteLine("Time elapsed: {0,10:N0}", this.stopwatch.ElapsedMilliseconds);
  19.             Console.WriteLine();
  20.         }
  21.     }
  22.  
  23.     class UsagaWordCounter
  24.     {
  25.         enum WordCountState
  26.         {
  27.             Init,
  28.             ComparingWord,
  29.             SkippingWord,
  30.             WhiteSpace
  31.         }
  32.  
  33.         public static int CountWords(string originString, string word)
  34.         {
  35.             int wordCounter = 0;
  36.             CharEnumerator wordCharEnumerator = word.GetEnumerator();
  37.             WordCountState state = WordCountState.Init;
  38.  
  39.             foreach (Char c in originString)
  40.             {
  41.                 if (c == ' ' || Char.IsPunctuation(c))
  42.                 {
  43.                     switch (state)
  44.                     {
  45.                         case WordCountState.Init:
  46.                         case WordCountState.SkippingWord:
  47.                             state = WordCountState.WhiteSpace;
  48.                             break;
  49.  
  50.                         case WordCountState.ComparingWord:
  51.                             if (!wordCharEnumerator.MoveNext())
  52.                             {
  53.                                 wordCounter++;
  54.                             }
  55.                             state = WordCountState.WhiteSpace;
  56.                             break;
  57.                     }
  58.                 }
  59.                 else
  60.                 {
  61.                     switch (state)
  62.                     {
  63.                         case WordCountState.Init:
  64.                         case WordCountState.WhiteSpace:
  65.                             wordCharEnumerator.Reset();
  66.                             wordCharEnumerator.MoveNext();
  67.                             state = (c == wordCharEnumerator.Current)
  68.                                 ? WordCountState.ComparingWord
  69.                                 : WordCountState.SkippingWord;
  70.                             break;
  71.  
  72.                         case WordCountState.ComparingWord:
  73.                             if (!wordCharEnumerator.MoveNext() ||
  74.                                 wordCharEnumerator.Current != c)
  75.                             {
  76.                                 state = WordCountState.SkippingWord;
  77.                             }
  78.                             break;
  79.                     }
  80.                 }
  81.             }
  82.  
  83.             if (state == WordCountState.ComparingWord && !wordCharEnumerator.MoveNext())
  84.             {
  85.                 wordCounter++;
  86.             }
  87.             return wordCounter;
  88.         }
  89.     }
  90.  
  91.     class Program
  92.     {
  93.         private static char[] SEPARATORS = { ' ', ',', '.', '!', ':', ';', '(', ')', '«', '»' };
  94.  
  95.         static int CountWordWithSplit(string sourseText, string word)
  96.         {
  97.             return sourseText.Split(SEPARATORS, StringSplitOptions.RemoveEmptyEntries).Count(x => x == word);
  98.         }
  99.  
  100.         static int CountWordManually(string sourceText, string word)
  101.         {
  102.             return UsagaWordCounter.CountWords(sourceText, word);
  103.         }
  104.  
  105.         static void Main(string[] args)
  106.         {
  107.             string warAndPeace = Resource1.warAndPeace;
  108.             string peaceWord = "мир";
  109.  
  110.             Console.WriteLine("Source data length: {0:N0}\n", warAndPeace.Length);
  111.  
  112.             Console.WriteLine("Split, cold iteration");
  113.             using (var mesurer = new TimeMesurer())
  114.             {
  115.                 Console.WriteLine("Words found: {0:N0}", CountWordWithSplit(warAndPeace, peaceWord));
  116.             }
  117.  
  118.             Console.WriteLine("Manual, cold iteration");
  119.             using (var mesurer = new TimeMesurer())
  120.             {
  121.                 Console.WriteLine("Words found: {0:N0}", CountWordManually(warAndPeace, peaceWord));
  122.             }
  123.  
  124.             for (int i = 0; i < 3; i++)
  125.             {
  126.                 Console.WriteLine("-----------");
  127.  
  128.                 Console.WriteLine("Split, hot iteration #{0}", i);
  129.                 using (var mesurer = new TimeMesurer())
  130.                 {
  131.                     Console.WriteLine("Words found: {0:N0}", CountWordWithSplit(warAndPeace, peaceWord));
  132.                 }
  133.  
  134.                 //GC.Collect();
  135.                 //GC.WaitForFullGCComplete();
  136.  
  137.                 Console.WriteLine("Manual, hot iteration #{0}", i);
  138.                 using (var mesurer = new TimeMesurer())
  139.                 {
  140.                     Console.WriteLine("Words found: {0:N0}", CountWordManually(warAndPeace, peaceWord));
  141.                 }
  142.             }
  143.  
  144.             Console.WriteLine("press any key...");
  145.             Console.ReadKey();
  146.         }
  147.     }
  148. }

ИИ поможет Вам:


  • решить любую задачу по программированию
  • объяснить код
  • расставить комментарии в коде
  • и т.д
Попробуйте бесплатно

Оцени полезность:

15   голосов , оценка 3.933 из 5

Нужна аналогичная работа?

Оформи быстрый заказ и узнай стоимость

Бесплатно
Оформите заказ и авторы начнут откликаться уже через 10 минут
Похожие ответы