Created
May 25, 2015 17:08
-
-
Save rbj325/6de89135dfbfab24d66d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// This method takes in a file path and returns the string with the most repeated characters in the txt file. | |
/// </summary> | |
/// <param name="filePath">This is the path to the txt file</param> | |
/// <returns>Word with the most repeated characters</returns> | |
private string findWordWithMostRepeatedCharacters(string filePath) | |
{ | |
var inputStr = getTextFromFile(filePath); | |
//Remove punctuation | |
inputStr = new string(inputStr.Where(c => !char.IsPunctuation(c)).ToArray()); | |
//Split the input string up into individual words | |
var words = inputStr.Split(' '); | |
var wordWithMostRepeatedChars = ""; | |
Tuple<char, int> mostRepeatedCharactersInWord = null; | |
Tuple<char, int> tempRepeatedCharactersInWord; | |
foreach (var word in words) | |
{ | |
//If the word is null, empty or whitespace ignore it. | |
if (String.IsNullOrWhiteSpace(word)) | |
continue; | |
//Group the current word string by character and select the tuple containing the actual character and count. Then sort by the highest count descending. | |
tempRepeatedCharactersInWord = word.ToLowerInvariant().GroupBy(x => x).Select(x => new Tuple<char, int>(x.Key, x.Count())).OrderByDescending(x => x.Item2).First(); | |
//Compare the character count to the stored value | |
if (mostRepeatedCharactersInWord == null || tempRepeatedCharactersInWord.Item2 > mostRepeatedCharactersInWord.Item2) | |
{ | |
mostRepeatedCharactersInWord = tempRepeatedCharactersInWord; | |
wordWithMostRepeatedChars = word; | |
} | |
} | |
return wordWithMostRepeatedChars; | |
} | |
/// <summary> | |
/// This method loads the contents of a file into a string. | |
/// </summary> | |
/// <param name="filePath">This is the path to the txt file</param> | |
/// <returns>The string representation of the content of the file.</returns> | |
private string getTextFromFile(string filePath) | |
{ | |
var text = ""; | |
try | |
{ | |
StreamReader streamReader = new StreamReader(filePath); | |
text = streamReader.ReadToEnd(); | |
streamReader.Close(); | |
} | |
catch (IOException ioe) | |
{ | |
Console.WriteLine("Unable to read file."); | |
} | |
catch (OutOfMemoryException oom) | |
{ | |
Console.WriteLine("This file is too big!"); | |
} | |
return text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment