I decided to solve the problem of finding the given characters in a string. And I solved it in two ways:
First (using a hash table to store values ββin ASCII for the characters we want to find):
static void Hash(string text, char[] charsToFind) { Dictionary<int,char> chars = new Dictionary<int,char>(); foreach (var letter in charsToFind) { chars[(int)letter] = letter; } foreach (var letter in text) { if (chars.ContainsKey((int)letter)) { if (letter == chars[(int)letter]) { Console.WriteLine("Element found at: {0}, value: {1}", (int)letter, letter); } } } }
And the second way (naive):
static void Naive(string text, char[] charsToFind) { foreach (var letter in text) { foreach (var character in charsToFind) { if ((int)letter == (int)character) { Console.WriteLine("Element found at: {0}, value: {1}", (int)letter, letter); } } } }
And everything works fine! The question I would like to ask is which one is better, and if there are even better solutions to this problem?
Thanks in advance!
source share