Search for characters in a string using a Hash table

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!

+4
source share
2 answers

Using LINQ:

 string input = "abc"; char[] charsToFind = new[] { 'a', '1', 'b' }; IEnumerable<int> ids = charsToFind.Select(ch => input.IndexOf(ch)); // { 0, -1, 1 } 

With a Hashset<T> , which is a shared hash table:

 HashSet<char> set = new HashSet<char>(input.ToCharArray()); ... 
+3
source

The first is a better approach, but the second is likely to be faster for a small number of characters.

Some comments on the first. In the first case, the use of a dictionary includes the cost of computing a hash and performing a search. If you knew ASCII characters, you can use an array to speed up the search.

Instead of doing "ContainsKey", you can do "TryGetValue" only once.

+1
source

All Articles