Click here to Skip to main content
13,836,160 members
Rate this:
Please Sign up or sign in to vote.
See more:
Hey. I'm new to C# and i wanted to ask how do I find a word who has been the most used. For example, i have a .txt file in which i have 3 words: Human;Mage;Human. How do I find that Human has been used the most and how do i return it ?

What I have tried:

Im not yet familiar with foreach loop and these values are stored in a list. So any help is good. Sorry for my bad english skills..
Updated 15-Sep-18 23:16pm

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

As with any task, break it down into smaller bits.
1) Read your file
2) Break it into words.
3) Identify different / duplicated words
4) Count them.
5) Find the highest count.

At each stage, get the ones before written, coded, tested , and perfect before moving on.

Now, the first I'm going to assume you know how to do.
The second (given your sample data) is simple: look at the String.Split Method (System) | Microsoft Docs[^]
The third is more complicated, and there are a whole load of ways to do it.
The fourth is probably most easily done as part of the third, once you have the third working.
The fifth is pretty trivial when the rest is done.

How would I do it? I'd use Linq, and a single line of code for 3, 4, and 5 all together - but that won't get you anywhere with your homework if you aren't good with loops yet!

So: Set up a pair of arrays, one holding strings, one holding integers (or better, a class holding a string and an integer then create an array of them if you've covered that yet).
Loop through your words, and see if each one is in the strings array already. If it aren't, add it.
When that's tested and working, add a counter: set the relevant integer to one when you add the word to the collection, increment it if it's already there.
Finally, look for the highest number in the integers collection, and print the associated word.

It's not complicated, not really - but it's your homework, so I'll give you no code!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Cookies | Terms of Service
Web01 | 2.8.190114.1 | Last Updated 16 Sep 2018
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100