user2387900
user2387900

Reputation: 215

Counting words from a string builder

I have a string builder which stores many words..for example, i did

StringBuilder builder = new StringBuilder();
builder.Append(reader.Value);

now, builder contains string as

" india is a great great country and it has many states and territories".. it contains many paragraphs.

I want that each word should be unique represented and its word count. example,

india: 1
great: 2
country: 1
and: 2

Also, this result should be saved in a excel file. But I am not getting the result.

I searched in google, but i am getting it by linq or by writing the words itself. Can you please help me out. I am a beginner.

Upvotes: 2

Views: 3785

Answers (3)

Sachin
Sachin

Reputation: 40970

You can use Linq to achieve it. Try something like this.

var result = from word in builder.Split(' ')
             group word by word into g
             select new { Word = g.Key, Count = g.Count() };

You can also convert this result into Dictionary object like this

Dictionary<string, int> output = result.ToDictionary(a => a.Word, a => a.Count);

So here each item in output will contains Word as Key and it's Count as value.

Upvotes: 4

Dimitar Dimitrov
Dimitar Dimitrov

Reputation: 15148

Well, this is one way to get the words:

IEnumerable<string> words = builder.ToString().Split(' ');

Upvotes: 1

xxbbcc
xxbbcc

Reputation: 17327

Look into using the String.Split() function to break up your string into words. You can then use a Dictionary<string, int> to keep track of unique words and their counts.

You don't really need a StringBuilder for this, though - a StringBuilder is useful when you contatenate strings together a lot. You only have a single input string here and you won't add to it - you'll split it up.

Once you finish processing all the words in the input string, you can write the code to export the results to Excel. The simplest way to do that is to create a comma-separated text file - search for that phrase and look into using a StreamWriter to save the output. Excel has built-in converters for CSV files.

Upvotes: 0

Related Questions