Thomas
Thomas

Reputation: 293

Using Dictionary to count the number of appearances

My problem is that I am trying to take a body of text from a text box for example "Spent the day with "insert famous name" '#excited #happy #happy"

then I want to count how many times each hashtag appears in the body, which can be any length of text.

so the above would return this

excited = 1

happy = 2

I Was planning on using a dictionary but I am not sure how I would implement the search for the hashtags and add to the dictionary.

This is all I have so far

 string body = txtBody.Text;

        Dictionary<string, string> dic = new Dictionary<string, string>();
        foreach(char c in body)
        {
            
        }

thanks for any help

Upvotes: 0

Views: 177

Answers (2)

spender
spender

Reputation: 120450

This will find any hashtags in a string of the form a hash followed by one or more non-whitespace characters and create a dictionary of them versus their count.

You did mean Dictionary<string, int> really, didn't you?

var input = "Spent the day with \"insert famous name\" '#excited #happy #happy";
Dictionary<string, int> dic = 
  Regex
    .Matches(input, @"(?<=\#)\S+")
    .Cast<Match>()
    .Select(m => m.Value)
    .GroupBy(s => s)
    .ToDictionary(g => g.Key, g => g.Count());

Upvotes: 2

mjolka
mjolka

Reputation: 831

This can be achieved with a couple of LINQ methods:

var text = "Spent the day with <insert famous name> #excited #happy #happy";
var hashtags = text.Split(new[] { ' ' })
    .Where(word => word.StartsWith("#"))
    .GroupBy(hashtag => hashtag)
    .ToDictionary(group => group.Key, group => group.Count());

Console.WriteLine(string.Join("; ", hashtags.Select(kvp => kvp.Key + ": " + kvp.Value)));

This will print

#excited: 1; #happy: 2

Upvotes: 2

Related Questions