Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Linq;
- using System.Text.RegularExpressions;
- namespace Searchers
- {
- public class Searcher
- {
- public static bool isExist(string fileName)
- {
- string errorMessage= "The file: " + fileName + " could not be found!";
- if (!File.Exists(fileName))
- {
- Console.WriteLine(errorMessage);
- return false;
- }
- else
- {
- return true;
- }
- }
- public static int GetWordsCount(string file)
- {
- var result = file.Split(' ').ToList();
- return result.Count;
- }
- public static int GetSymbolsCount(string file)
- {
- var counter = 0;
- foreach (var symbols in file)
- {
- counter++;
- }
- return counter;
- }
- public static void Result(string fileName)
- {
- var readOnlyFile = File.ReadAllText(fileName);
- Console.WriteLine("===============================");
- Console.WriteLine(readOnlyFile);
- Console.WriteLine("===============================");
- Console.WriteLine("The file contains " + GetSymbolsCount(readOnlyFile) + " symbols");
- Console.WriteLine("The file contains ~ " + GetWordsCount(readOnlyFile) + " words");
- Console.WriteLine("Type a word to search");
- String searchInput = Console.ReadLine();
- while (searchInput != "!!exit")
- {
- String pattern = "\\b";
- pattern += searchInput;
- pattern += "\\b";
- int count = Regex.Matches(File.ReadAllText(fileName),
- pattern,
- RegexOptions.IgnoreCase).Count;
- // IgnoreCase = ignore case sens
- Console.WriteLine(" --- {0} ===> {1}",searchInput,count);
- Console.WriteLine("Search a new word, or type !!exit");
- searchInput = Console.ReadLine();
- }
- // Do not forget to escape the pattern!
- }
- public static void Main()
- {
- // To search dinamically, just ask for a file:
- Console.WriteLine("Enter a file to search. Example: words.txt");
- String fileName = Console.ReadLine().Trim();
- if (isExist(fileName))
- {
- Result(fileName);
- }
- else
- {
- Console.WriteLine("Please enter a valid file name!");
- fileName = Console.ReadLine();
- if (isExist(fileName))
- {
- Result(fileName);
- }
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement