Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
1.00/5 (1 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..
Posted
Updated 15-Sep-18 22:16pm

1 solution

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!
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900