I decided to solve the problem of finding given characters in a string. And I solved it in two ways:
The first(using hash-table to keep the values in ASCII for the chars 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 (the 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’d like to ask is which one is the better and if there are even better solutions to this problem?
Thanks in advance!
Using LINQ:
With
Hashset<T>which is generic hash table: